使用反射在C#中创建动态LINQ语句 [英] Use reflection to make dynamic LINQ statements in C#
问题描述
如果我有类似LINQ的语句
If I have a LINQ statement like
x = Table.SingleOrDefault(o => o.id == 1).o.name;
如何使用反射使用传入的变量替换"id"和"name"?尝试时,我一直在获取未将对象引用设置为对象错误实例的信息.我的尝试是这样的
how can I replace "id" and "name" with passed in variables using reflection? I keep getting object reference not set to instance of an object errors when I try. My attempts are things like
x = (string)Table.SingleOrDefault(o => (int?)o.GetType().GetProperty(idString)
.GetValue(o, null) == 1).GetType().GetField(nameString).GetValue(x);
任何帮助都会很棒.谢谢.
Any help would be great. Thanks.
推荐答案
您应该使用表达式树而不是反射树.它将执行得更好,并且您将可以将其与LINQ to Objects和LINQ to SQL/Entities一起使用.
You should use Expression Trees instead of reflection. It will perform better, and you'll be able to use it with both LINQ to Objects and LINQ to SQL/Entities.
var source = new List<Test> { new Test { Id = 1, Name = "FirsT" }, new Test { Id = 2, Name = "Second" } };
var idName = "Id";
var idValue = 1;
var param = Expression.Parameter(typeof(Test));
var condition =
Expression.Lambda<Func<Test, bool>>(
Expression.Equal(
Expression.Property(param, idName),
Expression.Constant(idValue, typeof(int))
),
param
).Compile(); // for LINQ to SQl/Entities skip Compile() call
var item = source.SingleOrDefault(condition);
然后,您可以使用反射获得Name
属性(只需执行一次,因此可以使用反射来实现.
then, you can get Name
property using reflection (you'll do it just once, so it's fine to do it using reflection.
var nameName = "Name";
var name = item == null ? null : (string) typeof(Test).GetProperty(nameName).GetValue(item);
Test
类定义为
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
}
这篇关于使用反射在C#中创建动态LINQ语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!