开发者

Sorting ObservableCollection [duplicate]

This question already has answers here: Sort ObservableCollection<string> through C# (15 answers) Closed 6 years ago.

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 appr开发者_JS百科opriate 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……


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}}"


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

http://softcollections.codeplex.com/


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜