简体   繁体   中英

Find an item in a generic list by specifying multiple conditions

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.

试试这个:

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

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.

就个人而言,我更喜欢

Items.Find(item => item.ProductId == ProductID && item.ProductName.Equals("ABS001"));

使用&&而不是

var result = Items.Find(item => item.ProductId == ProductID && item.ProductName == "ABS001");

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"));

:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM