Single lambda expression


What is better to have two where clauses with && or just one where clause:

//two where clause:
list.Where(x => x.Prop1 == value1).Where(x => x.Prop2 == value2).ToList();
Or
//one where clause with &&
list.Where(x => x.Prop1 == value1 && x.Prop2 == value2).ToList();

It’s better to use the && with two tests in a single lambda. It will loop the list only once and call a delegate only half as often. The first version loops the list twice.

Just to be clear, this is the better option:

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

Which can also be written:

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

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*