Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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.

like image 450
MyNameIsJob Avatar asked Dec 20 '10 16:12

MyNameIsJob


2 Answers

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

like image 139
Quintin Robinson Avatar answered Oct 15 '22 18:10

Quintin Robinson


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.

like image 23
Jon Skeet Avatar answered Oct 15 '22 17:10

Jon Skeet