I have a List of DateTimeOffset
objects, and I want to insert new ones into the list in order.
List<DateTimeOffset> TimeList = ... // determine the order before insert or add the new item
Sorry, need to update my question.
List<customizedClass> ItemList = ... //customizedClass contains DateTimeOffset object and other strings, int, etc. ItemList.Sort(); // this won't work until set data comparison with DateTimeOffset ItemList.OrderBy(); // this won't work until set data comparison with DateTimeOffset
Also, how to put DateTimeOffset
as the parameter of .OrderBy()
?
I have also tried:
ItemList = from s in ItemList orderby s.PublishDate descending // .PublishDate is type DateTime select s;
However, it returns this error message,
Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'System.Collections.Gerneric.List'. An explicit conversion exist (are you missing a cast?)
Use the list. insert(0, x) element to insert the element x at the first position 0 in the list. All elements j>0 will be moved by one index position to the right. You create the list [5, 1, 3, 8, 7, 9, 2] and store it in the variable lst .
insert() Method. Use the insert() method when you want to add data to the beginning or middle of a list. Take note that the index to add the new element is the first parameter of the method.
Assuming your list is already sorted in ascending order
var index = TimeList.BinarySearch(dateTimeOffset); if (index < 0) index = ~index; TimeList.Insert(index, dateTimeOffset);
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With