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

1

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

问题描述

我有一个 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()的参数?

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"隐式转换为System.Collections.Gerneric.List".存在显式转换(您是否缺少演员表?)

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

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

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14