3

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?

1
  • OP -- Think it's worth flagging your question a dupe, or did you think it was different enough in some way to keep it around? Commented May 21, 2016 at 15:48

1 Answer 1

7

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Take care here, if the take two returns nothing; select l).Take(2).ToList(); It will be null instead of empty set, so this will crash.
@Ostmeistro No, Take(2) returns an empty set if there are no elements. Try e.g. Enumerable.Empty<int>().Take(2) - it will return an empty IEnumerable<int>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.