views:

112

answers:

3

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?

+2  A: 

A reference to an empty IEnumerable<T>.

Quintin Robinson
Excellent! That's what I was looking for. I wanted to be sure that I didn't have to check for null.
jasonh
Nitpick: A reference to an empty IEnumerable<T> - not a collection
Mark Seemann
Yup you are safe, it's sugary goodness!
Quintin Robinson
@Mark Yes I though about clarifying.
Quintin Robinson
+3  A: 

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

Ahmad Mageed
That makes it sound like it "knows" there's a count of 0 - which it doesn't. The returned value is an `IEnumerable<Int32>` which, when iterated over, will yield 0 items. It doesn't know that beforehand though - it has to try the predicate against each value to find out, and it doesn't do that until you ask it to.
Jon Skeet
@Jon: definitely, thanks for clarifying. As you mentioned in your post, it has to be used to determine the result.
Ahmad Mageed
+7  A: 

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!

Jon Skeet
I forgot all about lazy evaluation. *smacks self*
jasonh
Note that the "query" you're speaking of really is an IEnumerable of some sort which hasn't actually populated it's data...
RCIX