如何按顺序将项目列入列表?

任何人都可以教我如何在C#中按顺序将项目插入列表?

我有一个DateTimeOffset对象列表,我想按顺序将新的对象插入列表中。

List TimeList = ... // determine the order before insert or add the new item 

对不起,需要更新我的问题。

 List 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 

有人可以帮我把DateTimeOffset作为.OrderBy()的参数吗?

我也试过了

 ItemList = from s in ItemList orderby s.PublishDate descending // .PublishDate is type DateTime select s; 

但是,它会返回此错误消息,

无法将类型’System.Linq.IOrderedEnumerable’隐式转换为’System.Collections.Gerneric.List’。 存在显式转换(您是否错过了演员?)

修改你的LINQ,最后添加ToList():

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

或者,将排序列表分配给另一个变量

 var sortedList = from s in .... 

假设您的列表已按升序排序

 var index = TimeList.BinarySearch(dateTimeOffset); if (index < 0) index = ~index; TimeList.Insert(index, dateTimeOffset); 

@ LB对边缘情况的回答略有改进:

 public static class ListExt { public static void AddSorted(this List @this, T item) where T: IComparable { 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); } } 

使用.NET 4,您可以使用新的SortedSet否则您将使用键值集合SortedList

 SortedSet TimeList = new SortedSet(); // add DateTimeOffsets here, they will be sorted initially 

注意: SortedSet类不接受重复元素。 如果item已经在set中,则此方法返回false并且不会抛出exception。

如果允许重复,您可以使用List并使用它的Sort方法。

将项目插入特定索引

您可以使用:

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

要对集合进行排序,您可以使用linq:

 //This will sort the collection in ascending order List SortedCollection=from dt in TimeList select dt order by dt; 

将数据添加到列表后非常简单

 list.OrderBy(a => a.ColumnName).ToList(); 

找到所需的索引后Insert(index,object)可以使用Insert(index,object)

我接受了@Noseratio的回答并重新编写并将其与@Jeppe的答案结合起来,以获得适用于集合的函数(我需要它用于ObservableCollection of Paths)和类型,它不实现IComparable。

  ///  /// Inserts a new value into a sorted collection. ///  /// The type of collection values, where the type implements IComparable of itself /// The source collection /// The item being inserted public static void InsertSorted(this Collection collection, T item) where T : IComparable { InsertSorted(collection, item, Comparer.Create((x, y) => x.CompareTo(y))); } ///  /// Inserts a new value into a sorted collection. ///  /// The type of collection values /// The source collection /// The item being inserted /// An IComparer to comparer T values, eg Comparer<T>.Create((x, y) => (x.Property < y.Property) ? -1 : (x.Property > y.Property) ? 1 : 0) public static void InsertSorted(this Collection collection, T item, IComparer 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); } }