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) //?
{
}
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.Personally, I also think that the use of
Any()rather thanCount()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()orSingle()operators instead.