tags:

views:

78

answers:

2

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) //?
{

}
+5  A: 
if(!LinqResult.Any()) //?
{

}
Yuriy Faktorovich
+17  A: 

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 the first (or only) member of the sequence you should use either the First() or Single() operators instead.

LBushkin