IEnumerable 和 order [英] IEnumerable and order
问题描述
我有一个关于 IEnumerable
中的 order 的问题.
I have got a question about the order in IEnumerable
.
据我所知,遍历 IEnumerable 是伪代码可以写成如下方式:
As far as I am aware, 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?
因此,IEnumerable
不是保证排序的通用接口的正确方法.新的问题是什么接口或类应该用于具有顺序的不可变集合?只读集合
?IList
?它们都包含 Add()
方法(甚至在前一个中都没有实现).
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).
我自己的想法:IEnumerable
不提供有关排序的任何保证.正确的实现可以在不同的枚举中以不同的顺序返回相同的元素(考虑 SQL 查询)
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 an SQL query)
我知道 LINQ First()
,但是如果 IEnumerable
没有说明它的排序,这个扩展就毫无用处.
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/IEnumerable
可能会也可能不会保证订购.
IEnumerable/IEnumerable<T>
makes no guarantees about ordering, but the implementations that use IEnumerable/IEnumerable<T>
may or may not guarantee ordering.
例如,如果您枚举List
,则保证顺序,但如果您枚举HashSet
,则不提供此类保证,但两者都将是使用 IEnumerable
接口枚举.
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 和 order的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!