Sorts the items within the ObservableCollection by the given key selector. - CSharp System.Collections.ObjectModel

CSharp examples for System.Collections.ObjectModel:ObservableCollection

Description

Sorts the items within the ObservableCollection by the given key selector.

Demo Code


using System.Linq;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System;/*from ww  w. j a v  a 2 s  . c  o  m*/

public class Main{
        /// <summary>
        /// Sorts the items within the collection by the given key selector.
        /// </summary>
        /// <param name="collection">
        /// The collection to sort.
        /// </param>
        /// <param name="keySelector">
        /// The key selector.
        /// </param>
        /// <typeparam name="T">
        /// The type of item within the collection.
        /// </typeparam>
        /// <typeparam name="TKey">
        /// The type to order by.
        /// </typeparam>
        public static void SortBy<T, TKey>(this ObservableCollection<T> collection, Func<T, TKey> keySelector)
        {
            if (collection == null || collection.Count <= 1) return;

            var newIndex = 0;
            foreach (var oldIndex in collection.OrderBy(keySelector).Select(collection.IndexOf))
            {
                if (oldIndex != newIndex) collection.Move(oldIndex, newIndex);
                newIndex++;
            }
        }
}

Related Tutorials