I have been working a little bit with LINQ recently, and thanks to the help of some StackOverflowers I was able to get this statement working:
var traceJob =
from jobDefinition in service.JobDefinitions
where jobDefinition.Id == traceGuid
select jobDefinition;
if (traceJob != null && traceJob.Count() == 1)
{
traceJob.First().RunNow();
Console.WriteLine(traceJob.First().DisplayName + " Last Run Time: " + traceJob.First().LastRunTime);
}
However, I am confused because the piece that makes it work is the if(traceJob.Count() ==1)
. If I remove that section, then I get an ObjectNullRef
error saying that the enumeration of traceJob
yielded no results.
Now, to my knowledge, an if
statement checking the count should not actually alter the results of the Linq statement right? Can anyone explain to me why I am seeing this behavior?
No, it shouldn't. My guess is you have run into a case where the enumeration truly is empty, and by checking for a count > 0, First()
does not fail.
As a side note, Any()
may be a better check here as (depending on the underlying storage of your repository) it may be faster than Count()
:
if (traceJob != null && traceJob.Any())
{
traceJob.First().RunNow();
Console.WriteLine(traceJob.First().DisplayName + " Last Run Time: " + traceJob.First().LastRunTime);
}
var traceJob =
(from jobDefinition in service.JobDefinitions
where jobDefinition.Id == traceGuid
select jobDefinition).SingleOrDefault();
You can use singleOrDefault to check for a single result. It will return the result that matches the where
condition or null if no match is found. If more that one match for your query is found an exception is thrown.
This covers your tracejob == null
as well as tracejob.count == 1
conditions.
MSDN Article
I don't know the actual implementation of your "service" but usually linq queries actually populate their results only when requested. So Count() does change the state of traceJob, most probably populating internal collection. And it looks like First() doesn't populate internal collection or doesn't do it properly even though normally it should.
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