Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 easier on the application, right?

like image 737
Dan Avatar asked Mar 24 '10 08:03

Dan


1 Answers

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.

like image 65
Jelle Avatar answered Sep 27 '22 20:09

Jelle