IEnumerable< T> .Reverse是如何工作的?
我检查了反射器中的代码,但是我还没有找到它如何枚举通过一个集合向后?
I am checking out the code in the reflector, but I haven't yet found out how it can enumerate through a collection backwards?
因为没有计数信息和枚举总是从集合的开始开始,是吗?
Since there is no count information, and enumeration always starts from the "start" of the collection, right?
这是.NET框架中的一个缺点吗?成本是否高于常规枚举?
Is it a drawback in the .NET framework? Is the cost higher than regular enumeration?
简而言之,它缓冲一切,然后向后走。不太有效,但是从那个角度来看,OrderBy也不是。
In short, it buffers everything and then walks through it backwards. Not efficient, but then, neither is OrderBy from that perspective.
在LINQ-to-Objects中,有缓冲操作(Reverse,OrderBy,GroupBy等)缓冲操作(其中,Take,Skip等)。
In LINQ-to-Objects, there are buffering operations (Reverse, OrderBy, GroupBy, etc) and non-buffering operations (Where, Take, Skip, etc).
作为非缓冲的示例使用
IList< T>
执行
public static IEnumerable<T> Reverse<T>(this IList<T> list) {
for (int i = list.Count - 1; i >= 0; i--) {
yield return list[i];
}
}
请注意,这仍然是一个小错误你在迭代它时改变列表...所以不要这样做;-p
Note that this is still a little susceptible to bugs if you mutate the list while iterating it... so don't do that ;-p