ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

InsertSorted

Insert an item to a sorted List

Source

static class Extensions {

    public static int InsertSorted<T>(this IList<T> source, T value) where T : IComparable<T> {
        if (source is null) {
            throw new ArgumentNullException(nameof(source));
        }
        for (int i = 0; i < source.Count; i++) {
            if (value.CompareTo(source[i]) < 0) {
                source.Insert(i, value);
                return i;
            }
        }
        source.Add(value);
        return source.Count - 1;
    }

    public static int InsertSorted<T>(this IList<T> source, T value, IComparer<T> comparison) {
        if (source is null) {
            throw new ArgumentNullException(nameof(source));
        }
        for (int i = 0; i < source.Count; i++) {
            if (comparison.Compare(value, source[i]) < 0) {
                source.Insert(i, value);
                return i;
            }
        }
        source.Add(value);
        return source.Count - 1;
    }

    public static int InsertSorted<T>(this IList<T> source, T value, Comparison<T> comparison)  {
        if (source is null) {
            throw new ArgumentNullException(nameof(source));
        }
        for (int i = 0; i < source.Count; i++) {
            if (comparison(value, source[i]) < 0) {
                source.Insert(i, value);
                return i;
            }
        }
        source.Add(value);
        return source.Count - 1;
    }
}

Example

var l = new List<int>() {
    1,2,4,8,5,
};

l.Sort();

l.InsertSorted(0);
l.InsertSorted(6);
l.InsertSorted(9);
l.InsertSorted(3, Comparer<int>.Default);
l.InsertSorted(7, (x, y) => x.CompareTo(y));

foreach (var item in l) {
    Console.WriteLine(item);
}

Author: Fons Sonnemans

Submitted on: 27 aug. 2019

Language: C#

Type: IList<T>

Views: 4338