如何IEnumerable的< T> .Reverse工作? [英] How does IEnumerable<T>.Reverse work?

查看:184
本文介绍了如何IEnumerable的< T> .Reverse工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查了code的反射器,但我还没有发现它如何通过集合枚举倒退?

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?

推荐答案

总之,它缓冲一切,然后通过它向后走。效率不高,但随后,无论是排序依据从这一角度。

In short, it buffers everything and then walks through it backwards. Not efficient, but then, neither is OrderBy from that perspective.

在LINQ到对象,有缓冲操作(反向,排序依据,GROUPBY等)和非缓冲操作(其中,拿,跳过等)。

In LINQ-to-Objects, there are buffering operations (Reverse, OrderBy, GroupBy, etc) and non-buffering operations (Where, Take, Skip, etc).


由于采用了非缓冲逆向实施使用的IList℃的例子; T> ,考虑:

As an example of a non-buffering Reverse implementation using IList<T>, consider:

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

这篇关于如何IEnumerable的&LT; T&GT; .Reverse工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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