如何将项目插入列表顺序? [英] How to insert item into list in order?

查看:126
本文介绍了如何将项目插入列表顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能教我如何在C#中插入项目到列表顺序?



我的DateTimeOffset对象的名单,我想插入新成列表秩序。

 列表<&的DateTimeOffset GT; TimeList = ... 
//确定顺序插入前或新增项目



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

 列表< customizedClass> ITEMLIST = ... 
// customizedClass包含的DateTimeOffset对象等字符串,INT等

ItemList.Sort(); //这不会工作,直到与的DateTimeOffset
ItemList.OrderBy组数据比较(); //这不会工作,直到与的DateTimeOffset

组数据比较

谁能帮我把作为的DateTimeOffset .OrderBy()的参数?



我也试过

  ITEMLIST =从s在ITEMLIST 
排序依据s.PublishDate降// .PublishDate是DateTime类型
选择s;



但是,返回该错误消息,



< BLOCKQUOTE>

无法隐式转换类型'System.Linq.IOrderedEnumerable'到'System.Collections.Gerneric.List。显式转换存在(是否缺少强制转换?)



解决方案

修改您的LINQ,加了ToList()结尾:

  ITEMLIST =(从s在ITEMLIST 
排序依据s.PublishDate降
。选择所需S).ToList();



另外排序列表分配给另一个变量

  VAR排序列表=从s中.... 


Could anyone please teach me how to insert item into list in order in C#?

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

Could anyone please help me putting DateTimeOffset as the parameter of .OrderBy()?

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

解决方案

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 ....

这篇关于如何将项目插入列表顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆