Sorts a collection using the specified comparer descending. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:ICollection

Description

Sorts a collection using the specified comparer descending.

Demo Code


using System.Linq;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System;//from  ww w.  ja v  a2  s.  co  m

public class Main{
        /// <summary>
        /// Sorts a collection using the specified comparer descending.
        /// </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 SortDescending<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.OrderByDescending(comparer).Select(collection.IndexOf))
            {
                if (oldIndex != idx) collection.Move(oldIndex, idx);
                idx++;
            }
        }
}

Related Tutorials