LINQ动态表达式在List属性上调用Count()方法

时间:2015-07-06 17:00:09

标签: c# linq

使用LINQ Expression动态需要调用列表Count()方法。

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

 public class Bar
 {
      public ICollection<Foo> Data { get; set; }
 }

 var list = new List<Bar>();

需要动态构建一个谓词,它可以返回Bar的列表,其中包含Data.Count()&gt; 1使用表达式。

开始这样的事情..

MethodInfo method = typeof(Enumerable).GetMethods()
.Where(m => m.Name == "Count" && m.GetParameters().Length == 2).Single().MakeGenericMethod(typeof(Bar));

2 个答案:

答案 0 :(得分:2)

您要查找的Count方法只有一个参数:

public static int Count<TSource>(this IEnumerable<TSource> source)

您也可以使用Count属性,因为来源是ICollection

//build a lambda: (Bar bar) => bar.Data.Count > 1;
var barParam = Expression.Parameter(typeof (Bar), "bar");
var barDataProperty = Expression.PropertyOrField(barParam, "Data");
//since Data is of type ICollection, we can use the Count Property
var count = Expression.PropertyOrField(barDataProperty, "Count");
//if you do not want this dependency, call the Count() extension method:
var enumerableCountMethod = typeof (Enumerable).GetMethods()
    .First(method => method.Name == "Count" && method.GetParameters().Length == 1)
    .MakeGenericMethod(typeof(Foo));
var count2 = Expression.Call(enumerableCountMethod, barDataProperty);

var comparison = Expression.GreaterThan(count, Expression.Constant(1));
var comparison2 = Expression.GreaterThan(count2, Expression.Constant(1));

Expression<Func<Bar, bool>> expr = Expression.Lambda<Func<Bar, bool>>(comparison, barParam);
Expression<Func<Bar, bool>> expr2 = Expression.Lambda<Func<Bar, bool>>(comparison2, barParam);

var list = new List<Bar>();
var filteredList = list.Where(expr.Compile());
var filteredList2 = list.Where(expr2.Compile());

答案 1 :(得分:-1)

您可以使用predicate builder。例如:

IQueryable<Product> SearchProducts (params string[] keywords)
{
  var predicate = PredicateBuilder.False<Product>();

  foreach (string keyword in keywords)
  {
    string temp = keyword;
    predicate = predicate.Or (p => p.Description.Contains (temp));
  }
  return dataContext.Products.Where (predicate);
}
相关问题