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?)
very simple, after adding data into list
Modify your LINQ, add ToList() at the end:
Alternatively assign the sorted list to another variable
I took @Noseratio's answer and reworked and combined it with @Jeppe's answer from here to get a function that works for Collections (I needed it for an ObservableCollection of Paths) and type that does not implement IComparable.
To insert item to a specific index
you can use:
To sort the collection you can use linq:
You can use
Insert(index,object)
after finding index you want.Assuming your list is already sorted in ascending order