24

Most often we find generic list with code like:

CartItem Item = Items.Find(c => c.ProductID == ProductID);
Item.Quantity = Quantity;
Item.Price = Price;

So the above code finds and updates with other data, but if I want to find by multiple conditions, then how do I write the code?

I want to write code like:

CartItem Item = Items.Find(c => c.ProductID == ProductID and c.ProductName == "ABS001");

Please guide me for multiple conditions when we find generic list.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Thomas
  • 33,544
  • 126
  • 357
  • 626

5 Answers5

68

Try this:

CartItem Item = Items.Find(c => (c.ProductID == ProductID) && (c.ProductName == "ABS001"));
Spontifixus
  • 6,570
  • 9
  • 45
  • 63
Anton Sizikov
  • 9,105
  • 1
  • 28
  • 39
11

Try this:

Items.Find(c => c.ProductID == ProductID && c.ProductName == "ABS001");

The body of lambda expression is just a method. You can use in it all language constructs, as in regular method.

Dennis
  • 37,026
  • 10
  • 82
  • 150
5

Personally, I prefer

Items.Find(item => item.ProductId == ProductID && item.ProductName.Equals("ABS001"));
Anton Sizikov
  • 9,105
  • 1
  • 28
  • 39
Mr Z
  • 101
  • 1
  • 5
  • 1
    I tend to reverse the Equals to prevent a problem where item.ProductName is null. I would write `Items.Find(item => item.ProductId == ProductID && "ABS001".Equals(item.ProductName));` because you know "ABS001" is not null before run time. – Jay May 23 '18 at 11:03
3

Use && instead of and

var result = Items.Find(item => item.ProductId == ProductID && item.ProductName == "ABS001");
Zen
  • 244
  • 1
  • 3
  • 15
0

It annoys me when someone named a variable with the first char in uppercase, so (productID instead of ProductID):

CartItem Item = Items.Find(c => (c.ProductID == productID) && (c.ProductName == "ABS001"));

:)

tedi
  • 6,350
  • 5
  • 52
  • 67