Add element to Sorted IList - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Add element to Sorted IList

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*from www . j  av a 2s .  c  om*/

public class Main{
        public static void AddSorted<T>(this IList<T> list, T item, IComparer<T> comparer = null)
        {
            if (comparer == null)
                comparer = Comparer<T>.Default;

            int i = 0;
            while (i < list.Count && comparer.Compare(list[i], item) < 0)
                i++;

            list.Insert(i, item);
        }
}

Related Tutorials