Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting ObservableCollection [duplicate]

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……

like image 224
Pritesh Avatar asked Apr 27 '11 12:04

Pritesh


4 Answers

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}}"
like image 159
PVitt Avatar answered Nov 05 '22 08:11

PVitt


I think PVitt may have the best solution... however, i did find this SortedObservableCollection class that perhaps could help?

http://softcollections.codeplex.com/

like image 27
jonchicoine Avatar answered Nov 05 '22 07:11

jonchicoine


I implemented an ObservableCollectionView which supports sorting and filtering using a lambda (like LINQ but live) and item tracking:

https://mytoolkit.codeplex.com/wikipage?title=ObservableCollectionView

like image 2
Rico Suter Avatar answered Nov 05 '22 08:11

Rico Suter


You don't need to sort yourself, but can let WPF do it for you. See SortDescription, for example.

like image 1
Daniel Rose Avatar answered Nov 05 '22 09:11

Daniel Rose