MyNameIsJob
MyNameIsJob

Reputation: 2518

Linq with dot notation - which is better form or what's the difference between these two?

I've been reading Jon Skeet's C# In Depth: Second Edition and I noticed something slightly different in one of his examples from something I do myself.

He has something similar to the following:

var item = someObject.Where(user => user.Id == Id).Single();

Whereas I've been doing the following:

var item = someObject.Single(user => user.Id == Id);

Is there any real difference between the two? I know Jon Skeet is pretty much the c# god so I tend to think his knowledge in this area is better than mine so I might be misunderstanding something here. Hope someone can help.

Upvotes: 5

Views: 403

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1503280

I typically think in terms of "filter then take a single value". On the other hand, when it comes to Count I'll often use the version with the predicate. For Any I can go either way pretty easily depending on my mood :)

Ultimately it's unlikely to make any significant difference - use whichever is easier to understand at the time. I certainly wasn't trying to avoid using the versions with predicates etc - and I give some examples using them on P499.

While there are some situations with "definitely more readable" versions, many other cases are pretty much equally readable either way.

Upvotes: 3

Chris Taylor
Chris Taylor

Reputation: 53729

Specifically for Linq2Objects, I personally prefer using the Enumerable.Single(this, predicate) version directly, simply because adding the Enumerable.Where will introduce an additional enumeration which Enumerable.Single will pull the data from.

By using Enumerable.Single directly on the primary enumerable, no additional enumerations are started. I have never benchmarked this to evaluate the real performance impact, but why execute more code when you don't need to right? Especially if readability is not impacted, of course this last point is rather subjective.

Upvotes: 1

tanathos
tanathos

Reputation: 5606

The only thing I can notice is that the IL produced using the Where method is one row bigger than the second example (tested through LinqPAD).

IL_0042:  call        System.Linq.Enumerable.Where
IL_0047:  call        System.Linq.Enumerable.Single

instead of a single call to System.Linq.Enumerable.Single

IL_006B:  call        System.Linq.Enumerable.Single

Upvotes: 1

Quintin Robinson
Quintin Robinson

Reputation: 82375

The queries should be equal when the tree is evaluated, however depending on the target the actual execution could differ (IE L2S optimization).

Upvotes: 6

Related Questions