Search code examples
c#listlinqfiltercase-insensitive

unique LINQ to filter list by variables (case insensitive)


I have

public int practice_example6 (List<Car> cars)

I want to filter this list by Make that contains the word "Toyota" but not for that filter to be case sensitive. My other conditions are that SuggestedRetailPrice should be less than 30000.

I think I'm almost there but am confused about how to handle the case insensitive issue.

if (cars == null)
{
   return 0;
}
else
{
   List<Car> filtered = cars.Where(x => x.Make == "honda").ToList();
   List<Car> filtered2 = cars.Where(x => x.Make == "Honda").ToList();
   List<Car> filtered3 = cars.Where(x => x.SuggestedRetailPrice < 30000).ToList();
}

I'm also not sure on how to return 3 variables (filtered1,2,3) in one return statement. Perhaps just combine those 3 into one variable and then return that?

I'm a beginner and have researched about this. I would appreciate explanations not just fixes.

Thanks!

EDIT: I should not I have to do this without changing the function to IEnumerable practice_example6(List cars) - I know this would be ideal but there are constraints imposed.


Solution

  • You can try:

    string.Equals(x.Make, "Honda", StringComparison.CurrentCultureIgnoreCase);
    

    so something like:

    List<Car> filtered = cars.Where(x => string.Equals(x.Make, "Honda", StringComparison.CurrentCultureIgnoreCase)).ToList();
    

    Full method:

    if (cars == null)
    {
       return 0;
    }
    else
    {
       return cars.Count(x => string.Equals(x.Make, "Honda", StringComparison.CurrentCultureIgnoreCase) && x.SuggestedRetailPrice < 30000);
    }