Reputation: 14460
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
Upvotes: 48
Views: 58915
Reputation: 59
Here is what works for me:
public IQueryable SomeFunc()
{
IQueryable result = Repo.SomeLinqQuery();
if (result.GetEnumerator().MoveNext() == false)
{
throw new Exception("Results empty");
}
return result;
}
Upvotes: -1
Reputation: 4520
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>(); }
Upvotes: 4
Reputation: 437366
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
}
Upvotes: 94