IEnumerable和秩序 [英] IEnumerable and order

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

问题描述

我有一个关于为了的问题在的IEnumerable (或的IEnumerable< T> ,没关系)。

I've got a question about the order in IEnumerable (or IEnumerable<T>, does not matter).

我们知道,通过IEnumerable的迭代被伪code可以写在以下方式:

As we know, iterating through IEnumerable is pseudo-code can be written in the following way:

while (enumerable.HasNext())
{
    object obj = enumerable.Current;
    ...
}

现在,假设,一个需要在排序的收集工作。可IEnumerable的使用在这种情况下还是不如试试其他方法(即的IList )与指数化支持?

Now, assume, that one needs to operate on a sorted collection. Can IEnumerable be used in this case or is it better to try other means (i.e. IList) with indexation support?

在换句话说:是否的IEnumerable的合约做出一般的顺序任何保证

In other words: does the contract of IEnumerable make any guarantees about the order in general?

UPD :那么,的IEnumerable 不是一个适当的平均值为一个通用接口,保证订货。新的问题是什么接口或类用于一个不变的集合与秩序? ReadOnlyCollection还的IList ?它们都含有添加()方法(甚至未在前者实现的。)有什么建议?

UPD: So, IEnumerable is not a proper mean for a generic interface that guarantees ordering. The new question is what interface or class should be used for an immutable collection with order? ReadonlyCollection? IList? Both of them contain Add() method (even is not implemented in the former one.) Any suggestions?

PS我自己的想法:的IEnumerable 不提供有关订购任何保证。正确的实施可以在不同的枚举不同的顺序(考虑一个SQL查询)

P.S My own thoughts: IEnumerable does not provide any guarantees about the ordering. The correct implementation could return same elements in different order in different enumerations(consider a SQL query)

P.P.S。我知道LINQ的一(),但如果的IEnumerable 不说一个字关于它的订购,这种扩展是pretty的没用。

P.P.S. I am aware of LINQ First(), but if IEnumerable does not say a word about it's ordering, this extension is pretty useless.

推荐答案

的IEnumerable不保证顺序,但使用的IEnumerable可能会或可能无法保证有序的实现。

IEnumerable makes no guarantees about ordering, but the implementations that use IEnumerable may or may not guarantee ordering.

例如,如果您枚举名单,其中,T&GT; ,订单有保证,但如果枚举的HashSet&LT; T&GT; 没有这样的保证提供,但都将使用的IEnumerable&LT枚举; T&GT; 接口

For instance, if you enumerate List<T>, order is guaranteed, but if you enumerate HashSet<T> no such guarantee is provided, yet both will be enumerated using the IEnumerable<T> interface.

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

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