Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ results when there are no matches?

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?

like image 837
jasonh Avatar asked Oct 07 '09 17:10

jasonh


People also ask

What does Linq return when the results are empty?

It will return an empty enumerable.

What does a LINQ query return when no results are found?

if it finds a user, it adds it to the list (not database), and presents a message. if the user does NOT already exist, the program moves on to add the user.

Can ToList () return null?

ToList() returns null - Forums - IBM Support. If you have a Query that returns a empty set then ToList returns null. You would probably expect it to return an empty list (Count = 0), which is the case when using data providers for SQL Server.

What does first() do in c#?

The First() method returns the first element of a collection, or the first element that satisfies the specified condition using lambda expression or Func delegate.


2 Answers

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!

like image 173
Jon Skeet Avatar answered Nov 02 '22 23:11

Jon Skeet


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

like image 31
Ahmad Mageed Avatar answered Nov 03 '22 01:11

Ahmad Mageed