[英]How to return single value from anonymous Linq.Expressions.Expression
When using Entity Framework with LINQ I can code like: 在LINQ中使用Entity Framework时,我可以编写如下代码:
var a = context.Employee.Where(x => x.Name.Equals("Michael")).FirstOrDefault();
I'm curious how to create custom method with anonymous linq expression. 我很好奇如何使用匿名linq表达式创建自定义方法。 I have a model class and method as follow
我有一个模型类和方法如下
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
static T Single<T>(Expression<Func<T, bool>> predicate) where T : class
{
//This is from the database
List<Employee> employees = new List<Employee>
{
new Employee { Id = 1, Name = "Michael" },
new Employee { Id = 2, Name = "Derek" }
};
//I have no idea how to return single value of employees
//var expression = (BinaryExpression)predicate.Body;
//var left = expression.Left.Type.Name;
//Func<T, bool> func = predicate.Compile();
//T value = method(html.ViewData.Model);
//T t = (T)Convert.ChangeType(a, typeof(T));
//Employee emp = (Employee)Convert.ChangeType(t, typeof(Employee));
//var body = predicate.Body;
//var prop = (PropertyInfo)((MemberExpression)predicate.Body).Member;
//var propValue = prop.GetValue(func, null);
//var parameter = Expression.Parameter(typeof(T));
//var property = Expression.Property(parameter, expression.Member.Name);
//var equal = Expression.Equal(property, Expression.Constant(propValue));
//var lambda = Expression.Lambda<Func<T, bool>>(equal, parameter);
return null;
}
Calling the above method should be like 调用上面的方法应该是这样的
Employee emp = Single<Employee>(d => d.Name == "Michael");
You can call FirstOrDefault directly 您可以直接致电FirstOrDefault
var a = context.Employee.FirstOrDefault(x => x.Name.Equals("Michael"));
Or inside your function you can use 或者在你的功能里面你可以使用
return employees.FirstOrDefault(predicate);
Try to use IQuerable.Where
instead of IEnumerable.Where
First one uses Expression<Func<TSource, Boolean>>
as parameter. 尝试使用
IQuerable.Where
而不是IEnumerable.Where
首先使用Expression<Func<TSource, Boolean>>
作为参数。 Second uses Func<TSource, Boolean>
. 其次使用
Func<TSource, Boolean>
。
So you need to use AsQuerable()
and then Where()
So in your case it should look like 所以你需要使用
AsQuerable()
然后使用Where()
所以在你的情况下它应该是这样的
return employees.AsQuerable().Where(predicate).FirstOrDefault()
If you want to pass delegate
instead of Expression
you need to change method to static T Single<T>(Func<T, bool> predicate) where T : class
and then return employees.FirstOrDefault(predicate)
如果要传递
delegate
而不是Expression
,则需要将方法更改为static T Single<T>(Func<T, bool> predicate) where T : class
然后return employees.FirstOrDefault(predicate)
So you can use it this way 所以你可以这样使用它
Employee emp = Single<Employee>(d => d.Name == "Michael");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.