Home > other >  Filtering list of objects based on properties and their values
Filtering list of objects based on properties and their values

Time:01-02

Good evening, I'm building a basic console application to learn how to filter object list property data. I'm trying to filter a list of objects based on user selected object property and it's value, but I'm struggling to conceptualize how to connect user input to objects property, since properties do not have an index. For example, if we have a list of cars and user selects to filter by year and enters a specific year we would return those cars.

foreach(var car in listOfCars)
{
    if(...)
    {
        Console.WriteLine(car.Name);
        Console.WriteLine(car.Year);
    }
}

I can filter the data using wildcards, but how do you connect a user selected input (number) to a property?

CodePudding user response:

Well, it doesn't have to be a number:

Console.WriteLine("Filter by what? You can write YEAR, MAKE or MODEL");
var byWhat = Console.ReadLine();
Console.WriteLine("And what is the search term?");
var term = Console.ReadLine();

List<Car> filtered = new List<Car>();
if(byWhat == "YEAR"){
  int whatYear = int.Parse(term);
  foreach(var car in cars){
    if(car.Year == whatYear)
      filtered.Add(car);
  }
} else if(byWhat == ...) {
  ... foreach(...)
}

Feel free to convert that to using numbers if you want, and add some validation of input, case insensitivity.. etc..

The main point here is that you can make a variable that represents the common thing you'll get out; a filtered list of cars. You can do an if this then that, else if other then another.. and each if branch means the list of filtered cars ends up different.. But it's still a list of cars at the end and so by whatever process you did the filtering the common form of output can be treated in the same way.

Note; if you like you can flip it over and put the if inside the foreach - it's not appreciably slower

  • Related