Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert item into list in order?

Tags:

c#

sorting

insert

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?)

like image 702
Jerry Avatar asked Aug 29 '12 06:08

Jerry


People also ask

How do I add an element to a list in first position?

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 .

How do you add items to the middle of a list in Python?

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.


2 Answers

Assuming your list is already sorted in ascending order

var index = TimeList.BinarySearch(dateTimeOffset); if (index < 0) index = ~index; TimeList.Insert(index, dateTimeOffset); 
like image 83
L.B Avatar answered Oct 08 '22 07:10

L.B


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);     } } 
like image 32
noseratio Avatar answered Oct 08 '22 08:10

noseratio