Linq Where Clauses - Better to stack or combine?
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 eas开发者_开发百科ier on the application, right?
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.
The first would be slightly faster as it reduces the overhead somewhat. Other than that they are processed in basically the same way.
One noticable difference, though, is that the Color
property is compared before the Age
property in the second example. If you want a cheaper comparison to short circuit a more expensive one (so that the Color
property is only compared for the items where the Age
comparison is true), you should put the cheaper one in the last Where
call:
var blackOldCats =
cats
.Where(cat => cat.Colour == "noir")
.Where(cat => cat.Age > 7);
In this case there isn't much difference in the cost of the comparisons, but if one is much more expensive than the other it's good to know in which order they are evaluated.
精彩评论