Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Linq Result Is Empty

Tags:

c#

linq

If I have a linq query that looks like this, how can I check to see if there were no results found by the query?

var LinqResult =      from a in Db.Table     where a.Value0 == "ninja"     group a by a.Value1 into b     select new { Table = b};  if(LinqResult.Count() == 0) //? {  } 
like image 655
sooprise Avatar asked Jul 15 '10 20:07

sooprise


People also ask

What does LINQ return when the results are empty?

It will return an empty enumerable.

Is null in LINQ C#?

LINQ to SQL does not impose C# null or Visual Basic nothing comparison semantics on SQL. Comparison operators are syntactically translated to their SQL equivalents. The semantics reflect SQL semantics as defined by server or connection settings.

Can ToList return null?

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.


1 Answers

You should try to avoid using the Count() method as a way to check whether a sequence is empty or not. Phil Haack has an excellent article on his blog where he discusses this antipattern.

Count() must actually enumerate all elements of the sequence - which may be expensive if the sequence is based on multiple LINQ operations (or comes from a database).

You should use the Any() extension method instead - which only attempts to see if there is at least one element in the list, but will not enumerate the entire sequence.

if( !LinqResult.Any() ) {     // your code }  

Personally, I also think that the use of Any() rather than Count() better expresses your intent, and is easier to refactor or change reliably in the future.

By the way, if what you actually want is the first (or only) member of the sequence, you should use either the First() or Single() operators instead.

like image 184
LBushkin Avatar answered Sep 17 '22 13:09

LBushkin