C#为列表包含构建通用表达式树

时间:2019-07-11 10:24:34

标签: c# lambda expression

您好,我想创建一个通用的表达式树,该树返回包含结果的列表。

public static class Extension{
    public static List<T> WhereIn<T, T1>(IQueryable<T> query, IEnumerable<T1> keys, Expression<Func<T, T1>> param)
    {
    }
}

问题是我还想创建类似这样的东西:

var result = Extension.WhereIn(customers.AsQueryable(), stringList, c => c.Number.ToString());

到目前为止,这将适用于静态属性名称:

public static Expression<Func<T, bool>> FilterByCode<T, T1>(List<T1> codes, string propName)
{
    var methodInfo = typeof(List<T1>).GetMethod("Contains", 
        new Type[] { typeof(T1) });

    var list = Expression.Constant(codes);

    var param = Expression.Parameter(typeof(T), "j");
    var value = Expression.Property(param, propName);
    var body = Expression.Call(list, methodInfo, value);

    // j => codes.Contains(j.Code)
    return Expression.Lambda<Func<T, bool>>(body, param);
}

1 个答案:

答案 0 :(得分:1)

感谢Marc Gravell,我找到了解决方案:

  public List<T> WhereIn<T, TValue>(IQueryable<T> source, IEnumerable<TValue> keys, Expression<Func<T, TValue>> selector)
  {
     MethodInfo method = null;
     foreach (MethodInfo tmp in typeof(Enumerable).GetMethods(
        BindingFlags.Public | BindingFlags.Static))
     {
        if (tmp.Name == "Contains" && tmp.IsGenericMethodDefinition
                                   && tmp.GetParameters().Length == 2)
        {
           method = tmp.MakeGenericMethod(typeof(TValue));
           break;
        }
     }
     if (method == null) throw new InvalidOperationException(
        "Unable to locate Contains");
     var row = Expression.Parameter(typeof(T), "row");
     var member = Expression.Invoke(selector, row);
     var values = Expression.Constant(keys, typeof(IEnumerable<TValue>));
     var predicate = Expression.Call(method, values, member);
     var lambda = Expression.Lambda<Func<T, bool>>(
        predicate, row);
     return source.Where(lambda).ToList();
  }