繁体   English   中英

动态LINQ查询C#

[英]Dynamic linq query c#

我正在尝试在IEnumerable<T>上创建动态linq查询。 我要动态创建以下查询:

.OrderByDescending(n => n.TS)
.GroupBy(n => n.PID)
.Select(n => n.First())
.Where(n => !n.IsD)

我尝试过的如下:

var type = typeof(TSource);
ParameterExpression pe = Expression.Parameter(type, "n");
Expression tsExp = Expression.Property(pe, "TS");

MethodCallExpression orderByCallExpression = Expression.Call(
typeof(IEnumerable),
"OrderByDescending",
new Type[] { type.GetElementType() },
tsExp,
Expression.Lambda<Func<IEnumerable<TSource>>>(pe, new ParameterExpression[] { pe }));

MethodCallExpression groupByCallExpression = Expression.Call(
typeof(IEnumerable),
"GroupBy",
new Type[] { type.GetElementType() },
orderByCallExpression,
Expression.Lambda<Func<IEnumerable<TSource>>>(pe, new ParameterExpression[] { pe }));


//Here how to create Select and Where expressions
//The issue with Select is it contains First() function call. How can i make it?

query = query.Provider.CreateQuery<TSource>(groupByCallExpression);

我不知道我的第一次尝试是正确的,有人可以帮我创建此查询吗?

您可以尝试以下方法,而不是花一整天的时间:

var data = ((IEnumerable<object>)collection)
 .OrderByDescending(c => c.GetType().GetProperty("TS").GetValue(c))
 .GroupBy(c => c.GetType().GetProperty("PId").GetValue(c))
 .Select(c => c.First())
 .Where(c => !(bool)c.GetType().GetProperty("IsD").GetValue(c));

验证不存在于代码中-我假设对象必须具有这些属性,否则您将获得null引用异常。

希望能帮助到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM