how to know if my linq query returns null how to know if my linq query returns null wpf wpf

how to know if my linq query returns null


You can realise the result as a list:

var myQuery = (from Q in myDataContext select Q.Name).ToList();

Now you can check the number of items:

if (myQuery.Count > 0) ...

You could also use the Count() method on the original query, but then you would be running the query twice, once to count the items, and once to use them.


LINQ queries should never return null and you should not get an exception if the result is empty. You probably have an error in your code.

It looks like the code you posted is missing the table name. Are you sure that the code you posted is the code that is giving you problems?


Either you can convert it to list and then check the count

var result = (from Q in myDataContext select Q.Name).ToList();if(result.Count > 0){ // Perform some operation}

or you can do a null check as by default the linq queries return null instead of an empty list.

var result = (from Q in myDataContext select Q.Name);if(result != null){ // Perform some operation}