LINQ Expression for Contains

浪尽此生 提交于 2019-12-07 06:28:56

问题


I want to add dynamic expression in linq but facing issues on contains method it is working perfectly for Equal method

Problem is i'm getting FilterField dynamically how to replace in query

So far i had tried

List<int> Ids = new List<int>();  
**string filterField ="DEPARTMENT"; ==> Dynamic Field**

var eParam = Expression.Parameter(typeof(EmployeeDetail), "e");

var comparison = Expression.Equal(Expression.Property(eParam, filterField), Expression.Convert(Expression.Constant(Ids), Expression.Property(eParam, filterField).Type));

var lambda = Expression.Lambda<Func<EmployeeDetail, bool>>(comparison, eParam);

var countMonthly1 = ctx.tblMonthlyInput.Join(ctx.tblEmployee, a => a.CompanyId, b => b.CompanyId, (a, b) => b).Where(lambda).Count();

I want to make above query works for Contains method using linq expression

sample query :

var countMonthly = (from a in ctx.tblMonthlyInput
                    join b in ctx.tblEmployee on a.CompanyId equals b.CompanyId
                    where categoryId.Contains(a.CategoryId)  //want to make this dynamic
                    select a).Count() == 0;

回答1:


This will work for you:

void Main()
{
    var filterField = "Id";
    List<int> Ids = new List<int>();
    var eParam = Expression.Parameter(typeof(EmployeeDetail), "e");
    var method = Ids.GetType().GetMethod("Contains");
    var call = Expression.Call(Expression.Constant(Ids), method, Expression.Property(eParam, filterField));
    var lambda = Expression.Lambda<Func<EmployeeDetail, bool>>(call, eParam);
}

public class EmployeeDetail
{
    public int Id { get; set; }
}

First, you look for the Contains method on the type of Ids. Then we simply invoke it with Ids as the instance, and the property as the argument



来源:https://stackoverflow.com/questions/36547943/linq-expression-for-contains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!