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

编程入门 行业动态 更新时间:2024-10-25 10:33:12
本文介绍了LINQ 动态表达式对 List 属性调用 Count() 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

Using LINQ Expression dynamic need to call the list Count() method.

public class Foo { public int Id { get; set; } } public class Bar { public ICollection<Foo> Data { get; set; } } var list = new List<Bar>();

需要动态构建一个谓词,该谓词可以使用表达式返回具有Data.Count()> 1的Bar的列表.

Need to build a predicate dynamically which can return me the list of Bar which have Data.Count() > 1 using Expressions.

要开始这样的事情.

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

推荐答案

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

The Count method you are looking for has only 1 parameter:

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

您还可以使用 Count 属性,因为源是 ICollection :

You could also use the Count property since the source is an 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());

更多推荐

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

本文发布于:2023-10-30 12:02:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1542793.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   属性   方法   动态   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!