Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to check IQueryable result set is null

Tags:

c#

asp.net

linq

I just want to know what is the best way to check if an IQueryable result has no values.

eg. if we have a method like

public static IQueryable<Table> DisplayAll() {     var db = new DataContext();     var list= from data in db.Table select data;     return list; } 

and then we do something like this

var list = DisplayAll(); if(list != null) {      //do something --- in here even if the result set has no values it will      // go to this line. It just say `enumeration yielded no results` } 

Any possible way to check the result set has content or not??

Thanks

like image 249
huMpty duMpty Avatar asked Oct 19 '11 13:10

huMpty duMpty


People also ask

Does LINQ query return null?

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

Is IQueryable faster than list?

If it's a database query that's executed from the IQueryable that's 10,000 database queries, as opposed to just iterating an in-memory list 10,000 times. If you only iterate the query once then it will very possibly be more expensive to call ToList than to just iterate it directly.

What inherits from IQueryable?

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed.

IS NOT NULL check in LINQ?

The query needs to look for the values that is not null in any one of the list values (100 or 110 or 120). model = (from line in db. Bibs where line. TNo == "245" && (line.


2 Answers

list will never be null with LINQ; it will simply represent an "empty collection" if need be. The way to test is with the Any extension method:

if (list.Any()) {     // list has at least one item } 
like image 175
Jon Avatar answered Oct 14 '22 08:10

Jon


An exception will be thrown if IQueryable yeilds no result. I use:

using System.Data.Entity; //for Async support in EF var tQ = await _tableRepository.DisplayAll(); try { return await tQ.ToListAsync(); } catch { return null; } 

to trap the exception and return null; or an empty List if you prefer,

catch { return new List<Table>(); } 
like image 34
OzBob Avatar answered Oct 14 '22 08:10

OzBob