Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an IF Statement effect the outcome of my LINQ Statement?

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?

like image 362
wjhguitarman Avatar asked Nov 26 '12 16:11

wjhguitarman


3 Answers

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);
}
like image 187
D Stanley Avatar answered Oct 17 '22 02:10

D Stanley


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

like image 42
Amicable Avatar answered Oct 17 '22 01:10

Amicable


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.

like image 2
ElDog Avatar answered Oct 17 '22 01:10

ElDog