简体   繁体   中英

C# Linq .Find() return many results

I am trying to create a simple search function for my application. I am using Linq's .Find() method to search through a list of objects. It all works very well, the only problem I'm currently having is that I only get the first result. I know for a fact that there are more than one results to be had, but I only get one. Here is my code:

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;
}

I thought I could change Product searchResult into List<Product> searchResults in order to get a list of Products, then loop through that list. But that gave me an error saying:

Cannot implicitly convert type '.Product' to 'System.Collections.Generic.List<.Product>

Is there any way to get Linq's .Find() to return multiple results?

Use Where() and ToList() to get all objects, matching the condition into a List

replace

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

with

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

为此有一个FindAll方法:

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

Find() searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List.

You need to use FindAll() instead.

Microsoft explains the "Find()" method :"Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List."

I would suggest you to use this Where() method from Linq extension.

Don't forget to import "using System.Linq" in your current class.

Product searchResult = 

means you are declaring one element. The thing you need is a collection of products, like:

IEnumerable<product> searchResult  =

The easiest way to do it is to change Find() to where():

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

this will create some collection of product's. It will be easier to maintain as a list, so:

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

Read about IEnumerable interface :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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