Let's say I have the following class:
public class Person { public string FirstName { get; set; } public string SurName { get; set; } public int Age { get; set; } public string Gender { get; set; } }
In addition, I have the following method, and I access personal data through the repository.
public IEnumerable<Person> getPeople(string searchField, string searchTerm) {
As you can see, I get two parameters for the method: searchField
and searchTerm
.
searchField
is for the name of the field whose value will be used for filtering. searchTerm
is the value that will be used to compare with the return value (sorry if I don't understand here, but this is the most I can think of)
What I usually do is as follows:
public IEnumerable<Person> getPeople(string searchField, string searchTerm) { //_repo.GetAll() returns IEnumerable<Person> var model = _repo.GetAll(); switch(searchField) { case "FirstName": model = model.Where(x => x.FirstName == searchTerm); break; case "SurName": model = model.Where(x => x.SurName == searchTerm); break; //Keeps going } return model; }
Which will work perfectly. But if I make changes to my class, this code will have changes to break or to be in the absence of some functions if I add new properties to this class.
I am looking for something like below:
NOTE.
This code below is entirely in my imagination, and there is no such thing.
model = model.Where(x => x.GetPropertyByName(searchField) == searchTerm);
Am I flying too high here if this is not possible or is a complete idiot, if there is already a built-in way for this?