I have a list of objects that I want to filter based on some information. For example list of fruits that may have different fruits. from this list of fruits I want to get a new list of only fruits that match a certain criteria.
I have:
public List<Fruit> getFruitList(List<Fruit> allFruits, string fruitType, string fruitColor) {
List<Fruit> newFruits = allFruits.Where(f => f.typeOfFruit == fruitType)
.Where(f => f.fruitColor == fruitColor).ToList();
return newFruits;
}
but what happens if someone wants all fruit types, but wants to specify only on color (red, meaning red apples and strawberries should appear in the new list)? this means that the fruitType parameter can come as "All", which would not filter out any fruit based on that criteria.
the fruits in the list though, don't have a typeOfFruit value of "All" so the filter will return no results because no fruit had that value "All"
I saw something like this:
query = fruitColor == "All" ? query : query.Where(x => x.fruitColor == fruitColor);
query = fruitType == "All" ? query : query.Where(x => x.typeOfFruit == fruitType);
and build a query this way, however I don't know what kind of object this "query" is. Is it a string? or is there some sort of "Query" class that I can use to build a query expression?