排序依据和列表与IOrderedEnumerable [英] OrderBy and List vs. IOrderedEnumerable

查看:1193
本文介绍了排序依据和列表与IOrderedEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到下面的代码出现意外问题跑了。

I ran across an unexpected problem with the following code.

List<string> items = new List<string>();
items = items.OrderBy(item => item);

这代码生成错误:

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

Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)

看来我可以改变项目为类型的IEnumerable<的;串> 和错误消失。但我需要能够将项目添加到列表中,其中的IEnumerable 不支持。

It appears I can change items to be of type IEnumerable<string> and the error goes away. But I need to be able to add items to the list, which IEnumerable doesn't support.

有人能帮助我理解这个错误,什么最简单的解决方法是?它是安全的,简单地把结果?

Can someone help me understand this error, and what the easiest fix is? Is it safe to simply cast the result?

推荐答案

为什么不到位使用排序列表中的排序()实例方法;那么你可以添加项目以后,如果你喜欢的:

Why not just sort the list in place using the Sort() instance method; then you can add items to it later if you like:

List<string> items = GetSomeItems();
items.Sort();

或使用的有序集合像一个二叉搜索树。 的SortedSet< T> 可能适合该法案,根据您的需要。

Or, use an ordered collection like a binary search tree. SortedSet<T> might fit the bill, depending on your needs.

由他人提出的解决方案:<。 / p>

The solution suggested by the others:

items = items.OrderBy(item => item).ToList(); 



...创建与新秩序的原始项目另一份清单。如果您需要保留用于其他目的的原始顺序这仅仅是有用的; 。这是相当多浪费内存比排序到位名单

... creates another list with the original items in a new order. This is only useful if you need to preserve the original ordering for some other purpose; it's rather more wasteful of memory than sorting the list in place.

据了解错误,很简单:列表< T> 不是 IOrderedEnumerable℃的亚型; T> ,所以有两者之间没有隐式引用转换。编译器提出了明确的转换将满足编译器,但因为对象由归国它会在运行时失败排序依据< T> 不会从列表< T> 。

As far as understanding the error, it's simple: List<T> isn't a subtype of IOrderedEnumerable<T>, so there's no implicit reference conversion between the two. The explicit cast that the compiler suggests will satisfy the compiler, but it will fail at run time because the object returned by OrderBy<T> does not inherit from List<T>.

修改

的例子列表< T> ;的.sort(比较< T>),假设键入的MyType 有一个某些类型的T类型的财产,其中 T:IComparable的< T>

An example of List<T>.Sort(Comparison<T>), assuming the type MyType has a Key property of some type type T where T : IComparable<T>:

List<MyType> items = GetSomeItems();
items.Sort((a, b) => a.Key.CompareTo(b.Key));

这篇关于排序依据和列表与IOrderedEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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