Yip*_*Yay 6 c# linq optimization
优化以下类型语句的正确方法是什么:
IEnumerable<T> sequence = BuildSequence();
// 'BuildSequence' makes some tough actions and uses 'yield return'
// to form the resulting sequence.
Run Code Online (Sandbox Code Playgroud)
现在,如果我愿意只采取一些第一个元素,我可以使用类似的东西:
sequence.Take(5);
Run Code Online (Sandbox Code Playgroud)
所以,如果我的序列BuildSequence实际上包含数千个元素,我显然不希望所有元素都被构造,因为我只需要其中的5个.
是否LINQ优化了这种操作,或者我必须自己发明一些东西?
Mar*_*ell 14
该迭代器块(yield return)为您处理此; 迭代器块是一个流 API; 只有在MoveNext()迭代器(或on Dispose())上的每次调用期间才会发生工作.因为Take() 还没有读取整个流,这种行为将被保留.
但是请注意,某些操作需要在本地缓存数据- GroupBy和OrderBy最显着的; 但只要你使用非缓冲操作,你就可以了.
例如:
static IEnumerable<int> ReadInts() {
var rand = new Random();
while(true) yield return rand.Next();
}
...
int count = ReadInts().Take(10).Count(); // 10 - it doesn't loop forever
Run Code Online (Sandbox Code Playgroud)