LINQ results when there are no matches?

≡放荡痞女 提交于 2020-01-02 02:42:08

问题


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);

What would be in results at this point?


回答1:


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.

So you could do:

foreach (int x in results)
{
    Console.WriteLine("This won't happen");
}

Or:

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.

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!




回答2:


In this case it returns an IEnumerable<Int32> with a count of 0 items.




回答3:


A reference to an empty IEnumerable<T>.



来源:https://stackoverflow.com/questions/1533155/linq-results-when-there-are-no-matches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!