简体   繁体   English

动态LINQ查询C#

[英]Dynamic linq query c#

I am trying to create a dynamic linq query on IEnumerable<T> . 我正在尝试在IEnumerable<T>上创建动态linq查询。 The following query I want to create dynamically: 我要动态创建以下查询:

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

What I have tried is as under: 我尝试过的如下:

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

I don't know how much my first try is correct, can anyone please help me out to create this query? 我不知道我的第一次尝试是正确的,有人可以帮我创建此查询吗?

Instead of going all the way long, you can try this: 您可以尝试以下方法,而不是花一整天的时间:

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

The validation is not present in the code - i assume that the object must have these properties otherwise you will get null reference exception. 验证不存在于代码中-我假设对象必须具有这些属性,否则您将获得null引用异常。

Hope it helps! 希望能帮助到你!

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

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