为什么对IEnumerables使用标准扩展方法 [英] Why Standard Extension Method on IEnumerables

查看:40
本文介绍了为什么对IEnumerables使用标准扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在列表上使用标准的扩展方法时,例如 位置(...)

When i use a standard Extension Method on a List such as Where(...)

结果始终为 IEnumerable ,以及何时 您决定执行列表操作,例如 Foreach()

the result is always IEnumerable, and when you decide to do a list operation such as Foreach()

我们需要投射(不美观)或使用 ToList()扩展方法

we need to Cast(not pretty) or use a ToList() extension method that

(也许)使用消耗更多内存的新列表(是吗?):

(maybe) uses a new List that consumes more memory (is that right?):

List<string> myList=new List<string>(){//some data};

(编辑:此选项无效"

myList.Where(p=>p.Length>5).Tolist().Foreach(...);

(myList.Where(p=>p.Length>5) as List<string>).Foreach(...);

哪个是更好的代码,还是有第三种方法?

Which is better code or is there a third way?

修改: Foreach是一个示例,将其替换为BinarySerach

Foreach is a sample, Replace that with BinarySerach

myList.Where(p=>p.Length>5).Tolist().Binarysearch(...)

推荐答案

as绝对不是一个好方法,如果它奏效的话我会感到惊讶.

The as is definitely not a good approach, and I'd be surprised if it works.

关于什么是最佳",我建议使用foreach而不是ForEach:

In terms of what is "best", I would propose foreach instead of ForEach:

foreach(var item in myList.Where(p=>p.Length>5)) {
    ... // do something with item
}

如果您非常想要使用列表方法,也许:

If you desperately want to use list methods, perhaps:

myList.FindAll(p=>p.Length>5).ForEach(...);

或者实际上

var result = myList.FindAll(p=>p.Length>5).BinarySearch(...);

但请注意,此确实(与第一个不同)需要额外的数据副本,如果myList中有100,000个项目的长度大于5,则可能会很麻烦.

but note that this does (unlike the first) require an additional copy of the data, which could be a pain if there are 100,000 items in myList with length above 5.

LINQ返回IEnumerable<T>的原因是该(LINQ到对象)被设计为可组合和流式传输,如果转到列表,则不可能.例如,一些where/select等的组合应该严格地需要创建大量中间列表(实际上,LINQ不需要).

The reason that LINQ returns IEnumerable<T> is that this (LINQ-to-Objects) is designed to be composable and streaming, which is not possible if you go to a list. For example, a combination of a few where / select etc should not strictly need to create lots of intermediate lists (and indeed, LINQ doesn't).

当您考虑到并非所有序列都是有界的时,这一点尤为重要.有无限个序列,例如:

This is even more important when you consider that not all sequences are bounded; there are infinite sequences, for example:

static IEnumerable<int> GetForever() {
    while(true) yield return 42;
}
var thisWorks = GetForever().Take(10).ToList();

作为直到组成迭代器的ToList生成中间列表.但是,有一些缓冲操作,例如OrderBy,需要首先读取所有数据.大多数LINQ操作都是流式的.

as until the ToList it is composing iterators, not generating an intermediate list. There are a few buffered operations, though, like OrderBy, which need to read all the data first. Most LINQ operations are streaming.

这篇关于为什么对IEnumerables使用标准扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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