使用LINQ时从字符串访问lambda表达式中的属性 [英] Access property in lambda expression from string when using LINQ

查看:78
本文介绍了使用LINQ时从字符串访问lambda表达式中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该怎么做:

var result = db.MyTable.Where(x => x."MyProperty" == "Test" );

如您所见,我想访问"MyProperty",但将属性名称作为字符串输入.

As you can see I want to access "MyProperty" but give the property name as a sting.

推荐答案

您可以使用反射

x.GetType( ).GetProperty("MyProperty").GetValue( x, null ); 

尽管这可能行得通,但我不建议这样做,为什么不将您的where子句作为诸如以下的表达式传递:

although this might work, i wouldn't advise on doing this, why don't pass in your where clause as an expression like:

myMethod<T>(Expression<Func<T,bool>> where)

评论后的示例:

考虑以下类型:

example after comment:

consider the following type:

您会看到三个属性,其中名称为string类型,id为int类型.现在,如果我们将数据库上下文包装在这样的服务中

you see there are three properties where the name is of type string and id is of type int. now if we wrap our database context in a service like this

public class MyTypeOfXService
{
    private DataDataContext Context;
    public MyTypeOfXService()
    {
        Context = new DataDataContext("example code");
    }

    public IQueryable<MyTypeOfX> GetTypeOfX(Expression<Func<MyTypeOfX, bool>> where)
    {
        return this.Context.MyTypeOfXes.Where(where);
    }
}

在我们的get方法中,有一个Expression参数带有两个泛型,第一个是我们的类型x,第二个是布尔值.这种方法的优点是我们可以抽象所有的数据上下文创建,而只在代码中表达where子句,请参见最后一段代码:

in our get method there is an Expression parameter that takes two generics, the first is our type x and the second is a boolean. The advantage of this approach is that we can abstract all the data context creation and only express an where clause in our code see final piece of code:

class Program
{
    static void Main(string[] args)
    {
        var service = new MyTypeOfXService();

        var queryById = service.GetTypeOfX((mytype) => mytype.Id == 1);
        var queryByName = service.GetTypeOfX((mytype) => mytype.Name == "MyName");
        var queryByName = service.GetTypeOfX((mytype) => mytype.Name == "MyName" && mytype.Id == 1);
    }
}

如您所见,我们可以在任何属性或属性组合上构建where子句.

as you can see, we can build a where clause on any property or combination of properties.

这篇关于使用LINQ时从字符串访问lambda表达式中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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