How to sort BindingList<T>?

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


A quick way to implement a Sort on a BindingList is to use the constructor that takes a backing IList< T > as its argument. You can use a List<T> as the backing and gain its Sort capabilities.

Per the documentation

Use this BindingList to create a BindingList that is backed by list, which ensures that changes to list are reflected in the BindingList.

If your MyClass was defined as:

internal class MyClass
{
    public MyClass(string name, Int32 num)
    {
        this.Name = name;
        this.Num = num;
    }
    public string Name {get; set;}
    public Int32 Num {get; set;}
}

then you could do something like this to sort it on the Num field.

private List<MyClass> backing;
private BindingList<MyClass> bl;

    private void InitializeBindingList()
        {
            backing = new List<MyClass>();
            bl = new BindingList<MyClass>(backing);
            bl.Add(new MyClass("a", 32));
            bl.Add(new MyClass("b", 23));
            bl.Add(new MyClass("c", 11));
            bl.Add(new MyClass("d", 34));
            bl.Add(new MyClass("e", 53));
        }

    private void SortBindingList()
        {
            backing.Sort((MyClass X, MyClass Y) => X.Num.CompareTo(Y.Num));
            // tell the bindinglist to raise a list change event so that 
            // bound controls reflect the new item order
            bl.ResetBindings();
        }
    }

You need to call BindingList.ResetBindings method after sorting the backing list to notify any bound controls that the BindingList has changed and to update the control.

Tags:

C#

Winforms