簡體   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