In place sort for IList?

前端 未结 3 756
有刺的猬
有刺的猬 2020-12-20 01:07

Does .NET have an in place sort function for IList? I need to sort the collection itself, not create a new collection.

EDIT: The reason I need to do the sort in plac

3条回答
  •  我在风中等你
    2020-12-20 01:41

    Another take on the extension method solution by keeping it simple and using .NET's built-in sorting (also allowing for custom IComparers

    public static class IListExtensions
    {
        public static void Sort(this IList list)
        {
            var orderedList = list.OrderBy(i => i).ToArray();
    
            for( int i = 0; i < list.Count; ++i )
            {
                list[i] = orderedList[i];
            }
        }
    
        public static void Sort(this IList list, IComparer comparer )
        {
            var orderedList = list.OrderBy(i => i, comparer).ToArray();
    
            for (int i = 0; i < list.Count; ++i)
            {
                list[i] = orderedList[i];
            }
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var orig = new List() { 2, 3, 1 };
            var toOrder = orig;
    
            Console.Write("Orig: ");
            orig.ForEach(i => Console.Write("{0} ", i));
            toOrder.Sort();
            Console.Write("\nOrdered: ");
            toOrder.ForEach(i => Console.Write("{0} ", i));
            Console.Write("\nOrig: ");
            orig.ForEach(i => Console.Write("{0} ", i));
    
    
            Console.ReadLine();
        }
    
    }
    

提交回复
热议问题