where clause in C# Linq based on property name

asp.net asp.net-mvc c# entity-framework linq

Question

Say I'm enrolled in 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; }

}

Additionally, I am contacting person data through a repository and I have the following technique.

public IEnumerable<Person> getPeople(string searchField, string searchTerm) { 

    //_repo.GetAll() returns IEnumerable<Person>
    var model = _repo.GetAll(); 

    //Need the logic here for filtering

    return model;
}

As you can see, the function returns two parameters:searchField and searchTerm .

searchField is for the name of the field whose value will be filtered.searchTerm is the value to compare with the retrieved value, (I apologize if I am not making myself clear, but this is the best I can do.).

Normally, this is what I would do:

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;

}

it will function perfectly. But if I update my class, there's a chance that my code may malfunction or be missing certain methods if I add new attributes to this class.

I'm searching for anything along these lines:

NOTE :

This below code completely belongs to my imagination and there is no such a thing exists.

model = model.Where(x => x.GetPropertyByName(searchField) == searchTerm);

If this is impossible or if there is already a built-in method for doing this, am I soaring too high or am I just plain stupid?

1
8
10/11/2011 1:24:56 PM

Accepted Answer

5
10/11/2011 1:26:38 PM

Popular Answer

I believe the approach that comes next closely resembles what you had in mind, even if switching to a generic method would make more sense.

public IEnumerable<Person> getPeople(string searchField, string searchTerm) {
        PropertyInfo getter=typeof(Person).GetProperty(searchField);
        if(getter==null) {
            throw new ArgumentOutOfRangeException("searchField");
        }
        return _repo.GetAll().Where(x => getter.GetValue(x, null).ToString()==searchTerm);
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow