C# foreach(其中x=>;x.PROPERTY),如何设置属性?

C# foreach(其中x=>;x.PROPERTY),如何设置属性?,c#,reflection,lambda,propertyinfo,C#,Reflection,Lambda,Propertyinfo,我有一个对象学生,我通过下面的方法得到一个属性值 System.Reflection.PropertyInfo propValue = typeof(Student).GetProperty(s); 假设s(传入GetProperty的字符串)是名为“StudentName”的属性。然后,我希望基于该属性运行搜索,该属性存储在propValue中,例如: foreach (Student stu in formStudents.Where(x => x.propValue == "Joh

我有一个对象学生,我通过下面的方法得到一个属性值

System.Reflection.PropertyInfo propValue = typeof(Student).GetProperty(s);
假设s(传入GetProperty的字符串)是名为“StudentName”的属性。然后,我希望基于该属性运行搜索,该属性存储在propValue中,例如:

foreach (Student stu in formStudents.Where(x => x.propValue == "John"))
但是,这不起作用,因为x._uuu仅填写Student的属性(即使valueProp包含有效的Student属性)

我如何重写它,使其成为学生的实际值,或者其他什么方法对我有效


谢谢

因为
propValue
PropertyInfo
对象,所以需要使用该方法

然而,从问题的描述来看,您可能会通过查看库(也可从以下网站获得)来简化您的生活:


由于
propValue
PropertyInfo
对象,因此需要使用该方法

然而,从问题的描述来看,您可能会通过查看库(也可从以下网站获得)来简化您的生活:


调用从
.GetProperty
返回的
PropertyInfo
对象的
.GetValue(…)
方法:

如果您想:

var matchingStudents =
    from stu in formStudents
    let propertyValue = (string)propValue.GetValue(stu)
    where propertyValue == "John";
    select stu;
foreach (var student in matchingStudents)
    ...

调用从
.GetProperty
返回的
PropertyInfo
对象的
.GetValue(…)
方法:

如果您想:

var matchingStudents =
    from stu in formStudents
    let propertyValue = (string)propValue.GetValue(stu)
    where propertyValue == "John";
    select stu;
foreach (var student in matchingStudents)
    ...

请看一下
PropertyInfo
的方法,您已经有了它的实例。如果无法根据方法名猜出要使用什么,请查看文档。您将能够找到如何从对象获取该属性的值。请查看
PropertyInfo
的方法,您已经有了该方法的实例。如果无法根据方法名猜出要使用什么,请查看文档。您将能够找到如何从对象获取该属性的值。
foreach (Student stu in formStudents)
{
    var value = (string)propValue.GetValue(stu);
    if (value == "John")
    {
        ....
    }
}
var matchingStudents =
    from stu in formStudents
    let propertyValue = (string)propValue.GetValue(stu)
    where propertyValue == "John";
    select stu;
foreach (var student in matchingStudents)
    ...