繁体   English   中英

C#Linq .Find()返回许多结果

[英]C# Linq .Find() return many results

我正在尝试为我的应用程序创建一个简单的搜索功能。 我正在使用Linq的.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以获取Products列表,然后遍历该列表。 但这给了我一个错误:

无法将类型'.Product'隐式转换为'System.Collections.Generic.List <.Product>

有什么方法可以使Linq的.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()”方法:“搜索与指定谓词定义的条件匹配的元素,并返回整个List中的第一个匹配项。”

我建议您使用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();

了解有关IEnumerable接口的信息:)

暂无
暂无

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

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