简体   繁体   English

通过指定多个条件在通用列表中查找项目

[英]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. lambda表达式的主体只是一种方法。 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): 当有人使用大写的第一个char命名变量时,它会让我感到恼火,所以(productID而不是ProductID):

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

:) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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