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

Jer*_*rry 23 c# sorting insert

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

List<DateTimeOffset> TimeList = ...
// determine the order before insert or add the new item
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

另外,如何把DateTimeOffset参数作为.OrderBy()

我也尝试过:

ItemList = from s in ItemList
           orderby s.PublishDate descending    // .PublishDate is type DateTime
           select s;
Run Code Online (Sandbox Code Playgroud)

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

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

L.B*_*L.B 62

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

var index = TimeList.BinarySearch(dateTimeOffset);
if (index < 0) index = ~index;
TimeList.Insert(index, dateTimeOffset);
Run Code Online (Sandbox Code Playgroud)

  • **来自MSDN**:返回值如果找到项,则排序List <T>中项的从零开始的索引; 否则,负数是下一个元素的索引的按位补码,大于项,或者,如果没有更大的元素,则为Count的按位补码. (16认同)
  • 你能解释一下你的代码吗?如果他们不知道如何插入列表,我怀疑他们会知道`~index`会做什么. (5认同)

nos*_*tio 32

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于那些以前没有遇到过这个的人来说,“this”前面的@允许您使用保留字作为参数/变量。 (5认同)
  • @Baruch `@this` 是一个纯粹的常规变量名,通常用于引用由 C# 扩展方法扩展的对象。虽然“@this”是有效的 C# 变量名称,但您可以使用其他任何名称,例如“list”在这里可能有意义。 (3认同)
  • 在我无法使用SortedSet <>并且不得不重复.Sort()一个List的情况下,这个片段让我的性能提高了1000%. (2认同)

Tim*_*ter 11

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

SortedSet<DateTimeOffset> TimeList = new SortedSet<DateTimeOffset>();
// add DateTimeOffsets here, they will be sorted initially
Run Code Online (Sandbox Code Playgroud)

注意:SortedSet<T>该类不接受重复元素.如果item已经在set中,则此方法返回false并且不抛出异常.

如果允许重复,您可以使用a List<DateTimeOffset>并使用它的Sort方法.


Tom*_*nes 5

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

ItemList = (from s in ItemList
            orderby s.PublishDate descending   
            select s).ToList();
Run Code Online (Sandbox Code Playgroud)

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

var sortedList = from s in ....
Run Code Online (Sandbox Code Playgroud)