If I write a query for example:
var query = (from a in this.Context.Addresses where a.Active select a.Name);
then is it correct to say
if(query.Any())
return query.ToList();
return null;
notice the query didn't have a FirstOrDefault()
or ToList()
so I am wndering if .Any()
runs the query?
Yes - it has to, given that it's got to return true
or false
. It can't possibly do that without running the query.
If you're going to conditionally return ToList()
, you'd be better off writing:
var list = query.ToList();
return list.Any() ? list : null;
... or I'd actually recommend that you just return query.ToList()
anyway, as it's a lot easier to write code which uses an empty list than to have to special-case a null value.
See more on this question at Stackoverflow