簡體   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