Tra*_*s J 9 c# linq generics asp.net-mvc-3
类似:将字符串转换为Linq.Expressions或使用字符串作为选择器?
类似的那个:将Linq表达式作为字符串传递?
另一个问题有相同的答案:如何从C#中的字符串创建基于动态lambda的Linq表达式?
询问有这么多类似问题的事情的原因:
这些类似问题中接受的答案是不可接受的,因为他们都引用了4年前的一个库(授予它是由代码大师Scott Gu编写的)为旧框架(.net 3.5)编写的,除了链接作为答案.
有一种方法可以在代码中执行此操作,而不包括整个库.
以下是此情况的示例代码:
public static void getDynamic<T>(int startingId) where T : class
{
string classType = typeof(T).ToString();
string classTypeId = classType + "Id";
using (var repo = new Repository<T>())
{
Build<T>(
repo.getList(),
b => b.classTypeId //doesn't compile, this is the heart of the issue
//How can a string be used in this fashion to access a property in b?
)
}
}
public void Build<T>(
List<T> items,
Func<T, int> value) where T : class
{
var Values = new List<Item>();
Values = items.Select(f => new Item()
{
Id = value(f)
}).ToList();
}
public class Item
{
public int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
请注意,这并不是要将整个字符串转换为表达式,例如
query = "x => x.id == somevalue";
Run Code Online (Sandbox Code Playgroud)
但反而只是尝试使用字符串作为访问
query = x => x.STRING;
Run Code Online (Sandbox Code Playgroud)
Pau*_*ips 15
这是表达式树的尝试.我仍然不知道这是否适用于Entity框架,但我认为值得一试.
Func<T, int> MakeGetter<T>(string propertyName)
{
ParameterExpression input = Expression.Parameter(typeof(T));
var expr = Expression.Property(input, typeof(T).GetProperty(propertyName));
return Expression.Lambda<Func<T, int>>(expr, input).Compile();
}
Run Code Online (Sandbox Code Playgroud)
像这样称呼它:
Build<T>(repo.getList(), MakeGetter<T>(classTypeId))
Run Code Online (Sandbox Code Playgroud)
如果你可以使用a Expression<Func<T,int>>代替a Func,那么只需删除调用Compile(并更改签名MakeGetter).
编辑:在评论中,TravisJ询问他如何使用它:w => "text" + w.classTypeId
有几种方法可以做到这一点,但为了便于阅读,我建议首先引入一个局部变量,如下所示:
var getId = MakeGetter<T>(classTypeId);
return w => "text" + getId(w);
Run Code Online (Sandbox Code Playgroud)
重点是吸气剂只是一个功能,你可以像往常一样使用它.阅读Func<T,int>如下:int DoSomething(T instance)