在LINQ lambda表达式中使用字符串变量
我有一个类属性名称作为字符串变量,并且想在LINQ查询中使用它.下面的例子:
I have a class property name as string variable and want to use that in LINQ query. Below example:
public class Demo
{
public string prop1 {get; set;}
public string prop2 {get; set;}
public string prop3 {get; set;}
}
我可以做到
var data = db.Single<Demo>(d => d.prop1 == "value");
但是不知道运行时的属性是什么,并且像这样获取字符串参数
But don't know what's the property is at runtime and getting that string parameter like
string propname = "prop2";
是否有可能在lambda表达式d => d.propname == "value"
中使用它?我不确定是否可以,而且从逻辑上讲似乎是不可能的.所以想发布一个问题,看看是否有办法.请提出建议.
Is there any possibility to use that in lambda expression d => d.propname == "value"
? I am not sure it can be and logically doesn't seem possible. so thought of posting a question and see if there is a way. Please suggest.
请注意,Single()
调用发生在MongoDB C# Driver
之上,因此不确定反射是否会起作用.
To Note, that Single()
call is happening over MongoDB C# Driver
and thus not sure whether reflection would work.
(这是在意识到反射在特定情况下无济于事之前提供的原始文件.有关更新的答案,请参见下面的编辑)
如果您不介意使用反射,则可以执行以下操作:
If you don't mind using reflection, you could do:
var data = db.Single<Demo>(d => "value" == (string)typeof(Demo).GetProperty(propname).GetValue(d));
编辑
正如其他人在评论中所暗示的那样,要使此功能与MongoDB一起使用,您必须手动"构建表达式.
As others have hinted at in the comments, to make this work with MongoDB, you'll have to build the expression "by hand".
因此,如果我接受以下声明:
So, if I take the following statement:
var data = db.Single<Demo>(d => d.prop1 == "value");
我认为以下内容应等效,但要手动构建lambda表达式:
I believe that the following should be equivalent, but building the lambda expression by hand:
string propname = "prop1"; // you can now change this to any valid property name.
var parameterExpresion = Expression.Parameter(typeof(Demo), "d");
var binaryExpression = Expression.Equal(
Expression.Property(parameterExpresion, propname),
Expression.Constant("value"));
var lambda = Expression.Lambda<Func<Demo, bool>>(binaryExpression, parameterExpresion);
var data = db.Single<Demo>(lambda);
...除了现在,您应该可以将propname
的值更改为任何有效的属性名称,并且它应该可以正常工作.
... except that now, you should be able to change the value of propname
to any valid property name, and it should just work.
看看手动构建lambda时代码的详细程度,确实可以帮助我欣赏所有编译器的魔术,而无需我们注意.
Looking at how verbose the code gets when building lambdas manually really helps me appreciate all the compiler magic that happens without us ever noticing.