Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#Linq.Find()返回许多结果_C#_Linq - Fatal编程技术网

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

C#Linq.Find()返回许多结果,c#,linq,C#,Linq,我正在尝试为我的应用程序创建一个简单的搜索功能。我正在使用Linq的.Find()方法搜索对象列表。这一切都很好,我目前唯一的问题是我只得到了第一个结果。我知道有不止一个结果,但我只得到一个。这是我的密码: case 5: { //Search for Price Product searchResult = tempList.Find(x => x.getPrice() == searchPrice); if (searchResult != null) {

我正在尝试为我的应用程序创建一个简单的搜索功能。我正在使用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 searchResults
,以获得产品列表,然后循环浏览该列表。但这给了我一个错误,我说:

无法将类型“.Product”隐式转换为“System.Collections.Generic.List”

有没有办法让Linq的.Find()返回多个结果?

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

替换

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

List searchResult=templast.Where(x=>x.getPrice()==searchPrice.ToList();
有一种方法可用于此目的:

List<Product> products = tempList.FindAll(x => x.getPrice() == searchPrice);
List products=templast.FindAll(x=>x.getPrice()==searchPrice);
Find()
搜索与指定谓词定义的条件匹配的元素,并返回整个列表中的第一个匹配项

您需要使用
FindAll()

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

我建议您使用Linq扩展的这个

不要忘记在当前类中导入“使用System.Linq”

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

IEnumerable<product> searchResult  =
IEnumerable searchResult=
最简单的方法是将Find()更改为where():

IEnumerable searchResult=templast.Where(x=>x.getPrice()==searchPrice);
这将创建一些产品的集合。它将更容易作为列表进行维护,因此:

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

阅读IEnumerable接口:)

使用
.Where
而不是在末尾查找并放置
.ToList()
。问题解决请注意,
Find
不是LINQ的一部分。看起来您还真的需要接受.NET约定—属性而不是方法、命名等。
IEnumerable<product> searchResult = tempList.Where(x => x.getPrice() == searchPrice);
list<product> searchResult = tempList.Where(x => x.getPrice() == searchPrice).toList();