Mouayad
Mouayad

Reputation: 255

how to know if my linq query returns null

I have this linq query :

var myQuery = from Q in myDataContext
          select Q.Name

and when I try to do this : listView.ItemsSource = myQuery

it sometimes throws an exception because there are no elements in myQuery

I tried many ways like : if(myQuery.count!=0) or if(myQuery.Any()) but nothing worked , so how can I determine if my Query return null ?

Upvotes: 17

Views: 38285

Answers (5)

RajeshVerma
RajeshVerma

Reputation: 1137

Best approach is to check there is null(no items) in list use Any() instead of count()

var myQuery = (from Q in myDataContext select Q.Name).ToList(); Now you can check the number of items:

if (myQuery.Any()) ...

Upvotes: 0

Mayur Dhingra
Mayur Dhingra

Reputation: 1577

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
}

Upvotes: 2

Singleton
Singleton

Reputation: 3679

you can try this

var myQuery = from Q in myDataContext
if(myQuery != null ) 
{
  // TO SOME THING HERE
}

or u can additionally check that like if there is list in result

var myQuery = from Q in myDataContext
if(myQuery != null && myQuery.Count > 0  ) 
{
  // TO SOME THING HERE
}

Upvotes: 0

Guffa
Guffa

Reputation: 700342

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.

Upvotes: 17

Mark Byers
Mark Byers

Reputation: 838216

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?

Upvotes: 5

Related Questions