使用LINQ中的PropertyInfo对象查询集合 [英] Query a collection using PropertyInfo object in LINQ

查看:84
本文介绍了使用LINQ中的PropertyInfo对象查询集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a method with a signature like this

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
}

现在我要查询该集合以获取其

Now i want to query that collection for getting all the values whose

propertyName< 0

propertyName < 0

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

In a simple scenario it would be as easy as this

lst.where(u=>u.ID<0)

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

But here i don't have that ID property but have corresponding "PropertyInfo" object.

我应该如何实现呢?

友好的指导

推荐答案

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

You can lookup the property-value using property.GetValue(anObjectOfTypeT, null).

所以像这样:

var refreshedList =  lst.Where(l => ((int)(property.GetValue(l, null)) < 0).ToList();

这假定该属性始终为int类型.

This assumes the property will always be of type int though.

这篇关于使用LINQ中的PropertyInfo对象查询集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆