Pet*_*nov 5 c# linq performance linq-to-objects
我想说
IEnumerable<int> list = new int[] { 1, 2, 3 };
List<int> filtered = list.Select(item => item * 10).Where(item => item < 20).ToList();
Run Code Online (Sandbox Code Playgroud)
问题是有两次迭代还是只有一次.
换句话说,性能相当于:
IEnumerable<int> list = new int[] { 1, 2, 3 };
List<int> filtered = new List<int>();
foreach(int item in list) {
int newItem = item * 10;
if(newItem < 20)
filtered.Add(newItem);
}
Run Code Online (Sandbox Code Playgroud)
当您调用.ToArray方法时,对集合执行了一次迭代,因此两者应该是等效的..Select是一个投影,.Where是一个过滤器,都表示为原始数据集上的表达式树.
可以很容易地证明:
public class Foo: IEnumerable<int>
{
public IEnumerator<int> GetEnumerator()
{
yield return 1;
Console.WriteLine("we are at element 1");
yield return 2;
Console.WriteLine("we are at element 2");
yield return 3;
Console.WriteLine("we are at element 3");
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
class Program
{
static void Main()
{
var filtered = new Foo()
.Select(item => item * 10)
.Where(item => item < 20)
.ToList();
}
}
Run Code Online (Sandbox Code Playgroud)
运行时打印以下内容:
we are at element 1
we are at element 2
we are at element 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
180 次 |
| 最近记录: |