在LINQ中使用PropertyInfo对象查询集合

Meg*_*ind 5 c# linq reflection

我有一个像这样的签名的方法

void RefreshMethod<T>(IEnumerable<T> lst, string propertyName) where T:class
{
   Type type = typeof(T);
   PropertyInfo property = type.GetProperties().Single(u => u.Name == primaryKeyProperty);
  //query goes here
}
Run Code Online (Sandbox Code Playgroud)

现在我想查询该集合以获取其所有值

propertyName <0

在一个简单的场景中,它就像这样容易

lst.where(u=>u.ID<0)
Run Code Online (Sandbox Code Playgroud)

但在这里我没有那个ID属性,但有相应的"PropertyInfo"对象.

我应该怎么做到这一点.

善意的指导

Maa*_*ten 5

您可以使用查找属性值property.GetValue(anObjectOfTypeT, null).

所以类似于:

var refreshedList =  lst.Where(l => ((int)(property.GetValue(l, null)) < 0).ToList();
Run Code Online (Sandbox Code Playgroud)

这假设属性将始终为int类型.

  • @Maarten我的意思是,如果我必须对不同类型的多个属性执行此操作,除了为每个数据类型创建不同的var之外,还有其他方法吗? (2认同)