Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a linq query returns empty does it return null?

I have the following linq query:

     vm.logs = (from l in db.ActivityLogs
                   orderby l.Time
                   select l).Take(2);

If the db table is empty will this return null?

If not how can I detect if a query did return any information?

like image 692
Zapnologica Avatar asked Apr 11 '26 19:04

Zapnologica


1 Answers

It will return an IEnumerable<ActivityLog> with no elements.

To check if there are any elements, use the Any() method:

if(!logs.Any())
{
   Console.WriteLine("No elements found.");
}

Also note that as you've written it, vm.logs will be lazily evaluated, that is, it won't be fetched from the database until it is used. If you first do a .Any() and then later access the contents of the query, there will be two queries executed in the database. To avoid that, materialize (force the query to execute) by adding a ToList() to the query:

 vm.logs = (from l in db.ActivityLogs
               orderby l.Time
               select l).Take(2).ToList();
like image 96
Anders Abel Avatar answered Apr 14 '26 01:04

Anders Abel