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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12406750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:09:18  来源:igfitidea点击:

Find an item in a generic list by specifying multiple conditions

c#linqlambda

提问by Thomas

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.

当我们找到通用列表时,请指导我了解多个条件。

采纳答案by Anton Sizikov

Try this:

尝试这个:

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

回答by Dennis

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.

lambda 表达式的主体只是一个方法。您可以在其中使用所有语言结构,就像在常规方法中一样。

回答by Zen

Use &&instead of and

使用&&代替and

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

回答by Mr Z

Personally, I prefer

就个人而言,我更喜欢

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

回答by Tadej

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

当有人用大写的第一个字符命名变量时,这让我很恼火,所以(productID 而不是 ProductID):

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

:)

:)