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?
traceJob.Count() == 1totraceJob.Any()will perform better; as it returns immediately if an item is found rather than enumerating all items to get the count.