Sorting ObservableCollection

Pritesh picture Pritesh · Apr 27, 2011 · Viewed 14.7k times · Source

Suppose I have ObservableCollection of employee class

public ObservableCollection<Employee> employeeCollection = new ObservableCollection<Employee>();

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public double MobileNumber { get; set; }
    public string City { get; set; }
    public int Age { get; set; }

    public Employee() {}
}

now I am trying to sort the ObservableCollection (“employeeCollection”) by appropriate selection by user from combobox[it will be….Sort By FirstName….Sort By MobileNumber etc…]..

and it is required to get back sorted observable collection…. Means it should not be in form of “var” it should be ObservableCollection<Employee>

So I can assign back it to “ItemsSource” property of “ItemsControl”

Thanks……

Answer

PVitt picture PVitt · Apr 27, 2011

You can sort the view of the collection rather that sorting the collection itself:

// xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
<myView.Resources>
    <CollectionViewSource x:Key="ItemListViewSource" Source="{Binding Itemlist}">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="SortingProperty" />
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</myView.Resources>

And then you can use the CollectionViewSource as ItemSource:

ItemsSource="{Binding Source={StaticResource ItemListViewSource}}"