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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With