Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to know if my linq query returns null

Tags:

c#

.net

linq

wpf

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 ?

like image 571
Mouayad Avatar asked Nov 09 '10 10:11

Mouayad


People also ask

Does LINQ query return NULL?

It will return an empty enumerable. It won't be null.

Is NULL in LINQ?

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.

How do you handle NULL in LINQ query?

Select(q => { var attendanceList = new AttendanceBAL(). GetAttendanceListOf(q. _RollNumber); if (attendanceList == null) return null; return new StudentRecords() { _RollNumber = q. _RollNumber, _Class = q.

What does a LINQ query return when no results are found?

if it finds a user, it adds it to the list (not database), and presents a message. if the user does NOT already exist, the program moves on to add the user.


1 Answers

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.

like image 117
Guffa Avatar answered Sep 23 '22 03:09

Guffa