views:

99

answers:

2

When writing a method chain for LINQ, I can do the Where statements one of two ways:

var blackOldCats = cats.Where(cat => cat.Age > 7 && cat.Colour == "noir" )

Or

var blackOldCats = cats.Where(cat => cat.Age > 7).Where(cat => cat.Colour == "noir" )

Are there any benefits of one over the other?

Don't worry too much about the datatypes in this example, but if there are issues with datatypes, then that would be good to know too.

The obvious one is that the object is already referenced, so two properties hit at once is easier on the application, right?

+1  A: 

In your example they are the same and they are a matter of personal preference. Due to the deferred execution of LINQ, the collection will be iterated only once.

If you want to combine your expressions using an or operator, you can only use the first one.

Jelle
I didnt realise that the LINQ worked like that (although makes sense now). I was thinking that the first was going to be the fastest due to the combined comparison. Happy I put this Q up now.
burnt_hand
A: 
Guffa
Could you explain why to put the cheaper comparison at the end, instead of at the front? I'd do it the other way round, but only by instinct, not for any good reasons. =)
Jens
I wrote a small test application, that confirms my instinct here (two where clauses, one taking a short Thread.Sleep, the other being fast). Every where call seems to be executed on the result of the previous one, so the cheaper comparisons should be the first ones. Did I do a mistake?
Jens
Jens is right, your statement is backwards. I just tested it as well with a method that rights to console when its hit, and the methods are executed in sequence, left to right
burnt_hand
Yes, you are right. Although the last Where method is executed first, the first thing it does is to pull the result from the previous Where, causing the first condition to be evaluated before it evaluates it's own condition.
Guffa