简体   繁体   中英

Dynamic linq query c#

I am trying to create a dynamic linq query on IEnumerable<T> . 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.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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