問題描述
我有一個 DateTimeOffset
對象列表,我想將新對象按順序插入到列表中.
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
另外,如何將DateTimeOffset
作為.OrderBy()
的參數(shù)?
Also, how to put DateTimeOffset
as the parameter of .OrderBy()
?
我也試過了:
ItemList = from s in ItemList
orderby s.PublishDate descending // .PublishDate is type DateTime
select s;
但是,它會返回此錯誤消息,
However, it returns this error message,
無法將類型System.Linq.IOrderedEnumerable"隱式轉(zhuǎn)換為System.Collections.Gerneric.List".存在顯式轉(zhuǎn)換(您是否缺少演員表?)
Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'System.Collections.Gerneric.List'. An explicit conversion exist (are you missing a cast?)
推薦答案
修改你的LINQ,在末尾添加ToList():
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 ....
這篇關于如何按順序?qū)㈨椖坎迦肓斜?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!