Alexander Alexander - 2 months ago 13
C# Question

How to sort BindingList<T>?

I have several thousands MyClass objects stored in

BindingList<MyClass>
. I want to sort them by date property
MyClass.dt
.

Class BindingList doesn't support sorting directly. How I can sort
BindingList<T>
not making duplicate copies of all objects? I need to sort them as in ascending, as in descending order, please.

I don't need special class
SortableBindingList
as described in BindingList.Sort() to behave like a List.Sort(). I am searching for short solution in one o two lines of code.

Answer

Linq would work.

var sortedListInstance = new BindingList<MyClass>(unsortedListInstance.OrderBy(x => x.dt).ToList());

Keep in mind you get a shallow copy of the sorted list, not duplicate instances of MyClass.

Do not forget to include the namespace at the top of the code file System.Linq

Comments