通过指定多个条件在通用列表中查找项目
通常我们会找到包含以下代码的通用列表:
CartItem Item = Items.Find(c => c.ProductID == ProductID); Item.Quantity = Quantity; Item.Price = Price;
所以上面的代码找到并更新了其他数据,但如果我想通过多个条件找到,那么我该如何编写代码呢?
我想写代码如下:
CartItem Item = Items.Find(c => c.ProductID == ProductID and c.ProductName == "ABS001");
当我们找到通用列表时,请引导我了解多种情况。
试试这个:
CartItem Item = Items.Find(c => (c.ProductID == ProductID) && (c.ProductName == "ABS001"));
试试这个:
Items.Find(c => c.ProductID == ProductID && c.ProductName == "ABS001");
lambda表达式的主体只是一种方法。 您可以在其中使用所有语言结构,如常规方法。
就个人而言,我更喜欢
Items.Find(item => item.ProductId == ProductID && item.ProductName.Equals("ABS001"));
使用&&而不是和
var result = Items.Find(item => item.ProductId == ProductID && item.ProductName == "ABS001");
当有人使用大写的第一个char命名变量时,它会让我烦恼,所以(productID而不是ProductID):
CartItem Item = Items.Find(c => (c.ProductID == productID) && (c.ProductName == "ABS001"));
🙂