C# 林克 .find() 返回许多结果



我正在尝试为我的应用程序创建一个简单的搜索函数。我正在使用林克的.Find(( 方法搜索对象列表。一切都运行良好,我目前遇到的唯一问题是我只得到第一个结果。我知道有一个事实,有不止一个结果,但我只得到一个。这是我的代码:

case 5: {
    //Search for Price
    Product searchResult = tempList.Find(x => x.getPrice() == searchPrice);
    if (searchResult != null) {
        //Present Result
        searchTable.Rows.Add(convertIDValue(searchResult.getProductID()), searchResult.getTitle(), searchResult.getYear(), searchResult.getAmount(), searchResult.getPrice());
    }
    else {
        MessageBox.Show("No product with that price", "0 results");
    }
    break;
}

我想我可以Product searchResult更改为List<Product> searchResults以获得产品列表,然后循环浏览该列表。但这给了我一个错误说:

不能隐式转换类型 '。产品"到"系统.集合.通用列表<。产品>

有没有办法得到林克的.find(( 返回多个结果?

使用 Where()ToList() 获取所有对象,将条件匹配到List

取代

Product searchResult = tempList.Find(x => x.getPrice() == searchPrice);

List<Product> searchResult = tempList.Where(x => x.getPrice() == searchPrice).ToList();
有一个

FindAll方法可以达到这个目的:

List<Product> products = tempList.FindAll(x => x.getPrice() == searchPrice);

Find()搜索与指定谓词定义的条件匹配的元素,并返回整个 List 中的第一个匹配项。

您需要改用FindAll()

Microsoft解释了"Find(("方法:"搜索与指定谓词定义的条件匹配的元素,并返回整个列表中的第一个匹配项。

我建议您使用 Linq 扩展中的这个 Where(( 方法。

不要忘记在当前类中导入"using System.Linq"。

Product searchResult = 

表示您正在声明一个元素。您需要的是一系列产品,例如:

IEnumerable<product> searchResult  =

最简单的方法是将 Find(( 更改为 where((:

IEnumerable<product> searchResult = tempList.Where(x => x.getPrice() == searchPrice);

这将创建一些产品集合。作为列表维护会更容易,因此:

list<product> searchResult = tempList.Where(x => x.getPrice() == searchPrice).toList();

阅读有关 IE无数接口:)

最新更新