Linq-to-Objects Where the clause with 2 predicates

Is it better to have 2 Where clauses or 1 Where where with && &, or does it not matter?

list.Where(x => x.Prop1 == value1).Where(x => x.Prop2 == value2).ToList(); 

or

 list.Where(x => x.Prop1 == value1 && x.Prop2 == value2).ToList(); 
+4
source share
1 answer

It is better to use the second with two tests in one lambda. It will loop through the list only once and call the delegate only half as often. The first version iterates over the list twice.

To be clear, this is the best option:

 list.Where(x => x.Prop1 == value1 && x.Prop2 == value2).ToList(); 

What can also be written

 var results = (from x in list where x.Prop1 == value1 && x.Prop2 == value2 select x).ToList(); 

If you can avoid calling .ToList() and use it as an IEnumerable<T> , you will usually get even better perfection (unless you read it again and again).

+5
source

All Articles