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.
The queries should be equal when the tree is evaluated, however depending on the target the actual execution could differ (IE L2S optimization).
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.
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