How to insert item into list in order?

2019-02-04 05:53发布

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

8条回答
放我归山
2楼-- · 2019-02-04 06:22

very simple, after adding data into list

list.OrderBy(a => a.ColumnName).ToList();
查看更多
我只想做你的唯一
3楼-- · 2019-02-04 06:23

Modify your LINQ, add ToList() at the end:

ItemList = (from s in ItemList
            orderby s.PublishDate descending   
            select s).ToList();

Alternatively assign the sorted list to another variable

var sortedList = from s in ....
查看更多
ら.Afraid
4楼-- · 2019-02-04 06:25

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.

    /// <summary>
    /// Inserts a new value into a sorted collection.
    /// </summary>
    /// <typeparam name="T">The type of collection values, where the type implements IComparable of itself</typeparam>
    /// <param name="collection">The source collection</param>
    /// <param name="item">The item being inserted</param>
    public static void InsertSorted<T>(this Collection<T> collection, T item) where T : IComparable<T>
    {
      InsertSorted(collection, item, Comparer<T>.Create((x, y) => x.CompareTo(y)));
    }

    /// <summary>
    /// Inserts a new value into a sorted collection.
    /// </summary>
    /// <typeparam name="T">The type of collection values</typeparam>
    /// <param name="collection">The source collection</param>
    /// <param name="item">The item being inserted</param>
    /// <param name="ComparerFunction">An IComparer to comparer T values, e.g. Comparer&lt;T&gt;.Create((x, y) =&gt; (x.Property &lt; y.Property) ? -1 : (x.Property &gt; y.Property) ? 1 : 0)</param>
    public static void InsertSorted<T>(this Collection<T> collection, T item, IComparer<T> ComparerFunction)
    {
      if (collection.Count == 0)
      {
        // Simple add
        collection.Add(item);
      }
      else if (ComparerFunction.Compare(item, collection[collection.Count - 1]) >= 0)
      {
        // Add to the end as the item being added is greater than the last item by comparison.
        collection.Add(item);
      }
      else if (ComparerFunction.Compare(item, collection[0]) <= 0)
      {
        // Add to the front as the item being added is less than the first item by comparison.
        collection.Insert(0, item);
      }
      else
      {
        // Otherwise, search for the place to insert.
        int index = Array.BinarySearch(collection.ToArray(), item, ComparerFunction);
        if (index < 0)
        {
          // The zero-based index of item if item is found; 
          // otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.
          index = ~index;
        }
        collection.Insert(index, item);
      }
    }
查看更多
Animai°情兽
5楼-- · 2019-02-04 06:28

To insert item to a specific index

you can use:

DateTimeOffset dto;

 // Current time
 dto = DateTimeOffset.Now;

//This will insert the item at first position
TimeList.Insert(0,dto);

//This will insert the item at last position
TimeList.Add(dto);

To sort the collection you can use linq:

//This will sort the collection in ascending order
List<DateTimeOffset> SortedCollection=from dt in TimeList select dt order by dt;
查看更多
疯言疯语
6楼-- · 2019-02-04 06:28

You can use Insert(index,object) after finding index you want.

查看更多
Juvenile、少年°
7楼-- · 2019-02-04 06:31

Assuming your list is already sorted in ascending order

var index = TimeList.BinarySearch(dateTimeOffset);
if (index < 0) index = ~index;
TimeList.Insert(index, dateTimeOffset);
查看更多
登录 后发表回答