可变LINQ访问属性 [英] Linq access property by variable

查看:155
本文介绍了可变LINQ访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个类,如:

 公共类Foo 
{
公共字符串标题{获取;集;}
}

现在,让我们假设我有一个公开名单<富> myList中,我希望通过的LINQ如此过滤:

  VAR X = myList.Where(F = GT; f.Title == myvalue的); 



一切都是好的,明确的,直到如今。



但如何通过变量访问属性?是这样的:

  myProperty的字符串=标题; 

变种X = myList.Where(F => f.myProperty == myvalue的);


解决方案

您可以写一个扩展方法



 公共静态类MyExtensions 
{
公共静态对象的getProperty< T>(这件T OBJ,字符串名称),其中T:类
{
类型T = typeof运算(T);
返回t.GetProperty(名称).GetValue(OBJ,NULL);
}
}

和使用它像这样

  VAR X = myList.Where(F => f.GetProperty(标题)== myvalue的); 


Let's say I have a class like:

public class Foo
{
    public string Title {get;set;}
}

Now, let's assume I have a public List<Foo> myList which I want to filter by Linq as so:

var x = myList.Where(f => f.Title == myValue);

Everything is nice and clear until now.

But how can access the property by variable? Something like:

string myProperty = "Title";

var x = myList.Where(f => f.myProperty == myValue);

解决方案

You can write an extension method

public static class MyExtensions
{
    public static object GetProperty<T>(this T obj, string name) where T : class
    {
        Type t = typeof(T);
        return t.GetProperty(name).GetValue(obj, null);
    }
}

and use it like this

var x = myList.Where(f => f.GetProperty("Title") == myValue);

这篇关于可变LINQ访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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