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)
        nos*_*tio 32
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)
        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方法.
修改你的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)