问题描述
当没有匹配项时,LINQ函数究竟返回什么?以Where方法为例:
What exactly does a LINQ function return when there are no matches? Take the Where method, for example:
var numbers = Enumerable.Range(1, 10);
var results = numbers.Where(n => n == 50);
此时结果将是什么?
推荐答案
results
本身只是一个查询.直到您开始遍历它(显式地或通过诸如Count()
之类的调用),都没有检查是否有任何结果.只有当您枚举它时,一切都会发生.
results
itself is just a query. Until you start to iterate through it (either explicitly or via a call like Count()
), nothing has checked whether there are any results or not. It's only when you enumerate it that anything will happen.
所以您可以这样做:
foreach (int x in results)
{
Console.WriteLine("This won't happen");
}
或者:
Console.WriteLine(results.Any()); // Will print false
Console.WriteLine(results.Count()); // Will print 0
其中任何一个都会使谓词针对该范围内的每个项目进行评估...但是在此之前,根本不会调用谓词.
Any of these will cause the predicate to be evaluated against each item in the range... but before then, it won't be called at all.
这是一件很重要的事情,因为它意味着results
不能成为null
,同时又保留了惰性评估的功能-直到您尝试使用 results
,它是否应该为null
都不行!
This is an important thing to understand, because it means that results
couldn't be null
while retaining the feature of lazy evaluation - until you tried to use results
, it wouldn't have worked out whether it should be null
or not!
这篇关于没有匹配项时的LINQ结果吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!