Contains 的 LINQ 表达式

问题描述 投票:0回答:2

我想在 linq 中添加动态表达式,但面临 contains 方法的问题,它非常适合 Equal 方法

问题是我动态地得到

FilterField
如何在查询中替换

到目前为止我已经尝试过

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();

我想使用 linq 表达式使上述查询适用于 Contains 方法

示例查询:

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;
c# .net linq linq-expressions
2个回答
24
投票

这对你有用:

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; }
}

首先,在

Contains
类型上查找
Ids
方法。然后我们只需使用
Ids
作为实例,并将属性作为参数来调用它


0
投票
Imagine we've the Foo class with some objects as follow:
var lst = new List<Foo>()
{
  new Foo() { FirstName = "AmirHussein", LastName = "Naddaf", Age = 20 },
  new Foo() { FirstName = "Haji", LastName = "Khalilzadeh", Age = 40},
  new Foo() { FirstName = "Ghassem", LastName = "Yousefi", Age = 54}
};

Now, we want to do a search something as follow:
Select * From Foo where (Age = 20 Or Age = 54 Or LastName Like N'%zadeh%')

To do so in C#:

using System.Linq.Expressions;
...

var param = Expression.Parameter(typeof(Foo), "x");
var val = Expression.Constant(20, typeof(Int32));
var query = Expression.Equal(Expression.PropertyOrField(param, "Age"), val);

var val2 = Expression.Constant(54, typeof(Int32));
var query2 = Expression.Equal(Expression.PropertyOrField(param, "Age"), val2);

var val3 = "zadeh";
var method = val3.GetType().GetMethod("Contains");
var query3 = Expression.Call(Expression.PropertyOrField(param, "LastName"), 
method, Expression.Constant(val3));
            
query = Expression.OrElse(query, query2);
query = Expression.OrElse(query, query3);

var lambdaExp = Expression.Lambda<Func<Foo, bool>>(query, param);
var q = lambdaExp.Compile();

var res = lst.Where(q);
        
foreach(var item in lst)
{
    MessageBox.Show(item.FirstName + ' ' + item.LastName);
}
© www.soinside.com 2019 - 2024. All rights reserved.