Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 动态linq查询c_C#_Linq - Fatal编程技术网

C# 动态linq查询c

C# 动态linq查询c,c#,linq,C#,Linq,我试图在IEnumerable上创建一个动态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"); Expre

我试图在IEnumerable上创建一个动态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引用异常


希望有帮助

那么查询需要是动态的呢?到目前为止,您只是将所有内容都构建为常量,在这种情况下,您应该让编译器通过使用lambdas来为您完成这项工作。查询需要是动态的,因为我必须将其应用于反射中的对象,该对象的类型在编译时未知。正如我所说,我们需要知道查询的动态内容。你想让尽可能少的事情成为动态的,所有已知不变的事情都可以在不从头开始构建的情况下完成。