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) //? { }
It will return an empty enumerable.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With