Sorts ObservableCollection using the specified comparer. - CSharp System.Collections.ObjectModel

CSharp examples for System.Collections.ObjectModel:ObservableCollection

Description

Sorts ObservableCollection using the specified comparer.

Demo Code


using System.Linq;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System;/*from  w w w .j a va2  s.c om*/

public class Main{
        /// <summary>
        /// Sorts a collection using the specified comparer.
        /// </summary>
        /// <typeparam name="T">
        /// The type of item in the collection.
        /// </typeparam>
        /// <typeparam name="TKey">
        /// The key.
        /// </typeparam>
        /// <param name="collection">
        /// The collection to sort.
        /// </param>
        /// <param name="comparer">
        /// The comparer to use.
        /// </param>
        public static void Sort<T, TKey>(this ObservableCollection<T> collection, Func<T, TKey> comparer)
        {
            if (collection == null || collection.Count <= 1) return;

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

Related Tutorials