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

查看:123
本文介绍了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

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

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