How to insert item into list in order?
A slightly improved version of @L.B.'s answer for edge cases:
public static class ListExt
{
public static void AddSorted<T>(this List<T> @this, T item) where T: IComparable<T>
{
if (@this.Count == 0)
{
@this.Add(item);
return;
}
if (@this[@this.Count-1].CompareTo(item) <= 0)
{
@this.Add(item);
return;
}
if (@this[0].CompareTo(item) >= 0)
{
@this.Insert(0, item);
return;
}
int index = @this.BinarySearch(item);
if (index < 0)
index = ~index;
@this.Insert(index, item);
}
}
With .NET 4 you can use the new SortedSet<T>
otherwise you're stuck with the key-value collection SortedList
.
SortedSet<DateTimeOffset> TimeList = new SortedSet<DateTimeOffset>();
// add DateTimeOffsets here, they will be sorted initially
Note: The SortedSet<T>
class does not accept duplicate elements. If item is already in the set, this method returns false and does not throw an exception.
If duplicates are allowed you can use a List<DateTimeOffset>
and use it's Sort
method.
Assuming your list is already sorted in ascending order
var index = TimeList.BinarySearch(dateTimeOffset);
if (index < 0) index = ~index;
TimeList.Insert(index, dateTimeOffset);