Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

wpf - Sorting ObservableCollection<T>

I have Two separate observable Collection where T is a user defined class. These collections are binded to List View and Tree View. I want to show the items of the collections in sorted order. I don't seem to find any sort function on the List and Tree view. Elements in Collections can be removed/added on run time. What is the best way to achieve this?

Thanks in advance. Cheers!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can implement this behaviour yourself quite easily using the internal Move method by extending the ObservableCollection<T> class. Here is a simplified example:

public class SortableObservableCollection<T> : ObservableCollection<T>
{
    public SortableObservableCollection(IEnumerable<T> collection) : 
        base(collection) { }

    public SortableObservableCollection() : base() { }

    public void Sort<TKey>(Func<T, TKey> keySelector)
    {
        Sort(Items.OrderBy(keySelector));
    }

    public void Sort<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer)
    {
        Sort(Items.OrderBy(keySelector, comparer));
    }

    public void SortDescending<TKey>(Func<T, TKey> keySelector)
    {
        Sort(Items.OrderByDescending(keySelector));
    }

    public void SortDescending<TKey>(Func<T, TKey> keySelector, 
        IComparer<TKey> comparer)
    {
        Sort(Items.OrderByDescending(keySelector, comparer));
    }

    public void Sort(IEnumerable<T> sortedItems)
    {
        List<T> sortedItemsList = sortedItems.ToList();
        for (int i = 0; i < sortedItemsList.Count; i++)
        {
            Items[i] = sortedItemsList[i];
        }
    }
}

Thanks to @ThomasLevesque for the more efficient Sort method shown above

You can then use it like this:

YourCollection.Sort(c => c.PropertyToSortBy);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...