Question

I have an Object Student, I get one of the property's values by this method below

System.Reflection.PropertyInfo propValue = typeof(Student).GetProperty(s);

Let's say that s (the string I passed into the GetProperty) was the property called "StudentName". I would then like to run a search based off that property, which was stored in propValue, such as:

foreach (Student stu in formStudents.Where(x => x.propValue == "John"))

However this does not work, as x.__ only fills in with properties of Student (even though valueProp contains a valid property of Student).

How can I override this so that is reads propValue as an actual value of student, or what other method will work for me?

Thank you

Was it helpful?

Solution

Since propValue is a PropertyInfo object, you need to use the GetValue method

foreach (Student stu in formStudents.Where(x => ((string)propValue.GetValue(x, null)) == "John"))

However, from the description of problem, it seems like you might make your life easier by looking into the Dynamic Linq library (also available on NuGet):

using System.Linq.Dynamic;

...

foreach (Student stu in formStudents.Where("StudentName = @0", "John"))

OTHER TIPS

You call the .GetValue(...) method of the PropertyInfo object you got back from .GetProperty(s):

foreach (Student stu in formStudents)
{
    var value = (string)propValue.GetValue(stu);
    if (value == "John")
    {
        ....
    }
}

You can rewrite to LINQ if you want to:

var matchingStudents =
    from stu in formStudents
    let propertyValue = (string)propValue.GetValue(stu)
    where propertyValue == "John";
    select stu;
foreach (var student in matchingStudents)
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top