列表上的Lambda并使用反射来获取属性名称
假设您有一个通用类,其中有一个 List
现在考虑这个基本的 lambda 表达式:
var result = Items.FindAll(x => x.Name = "Filip");
只要我们知道,这才有效T
的属性,当它是泛型类型时,您不需要这些属性。
因此,我想使用反射来获取属性,如下所示:
PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public);
并以某种方式将其与上面的 Lambda 表达式结合起来,以便它搜索Type的所有公共属性,看看是否包含“Filip”,此时我不在乎property-name是否为Name。
这可能吗?
Let's say you have a Generic Class which have a List<T> Items;
Now think of this basic lambda expression:
var result = Items.FindAll(x => x.Name = "Filip");
This will only work as long as we Know the Properties of T
, which you don't when it's a generic type.
Therefore I would like to fetch the properties using Reflection like this:
PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public);
and somehow combind that with the above Lambda-expression so that it searches All the public properties of the Type and see if it contains "Filip", at this time I do not care if the property-name is Name or not.
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显然,这是一个简单、乐观的字符串比较(例如,您可能想要使用 string.Compare),但这应该使想法变得清晰。
编辑
dtb 在使用表达式树方面提出了很好的建议。您可以像这样更快地完成您所追求的事情:
这将允许您执行如下操作:
Obviously this is a simplistic, optimistic string comparison (you might want to use
string.Compare
, for example), but this should make the idea clear.Edit
dtb makes a good suggestion in using expression trees. You could accomplish what you're after in a faster fashion like this:
This will allow you to do something like this:
您可以使用表达式树即时构建 lambda:
You can use expression trees to construct a lambda on-the-fly: