通过收集属性排序动态LINQ [英] Sorting Dynamic LINQ By Collection Property

查看:132
本文介绍了通过收集属性排序动态LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用System.Linq.Dynamic,并具有以下简化结构(型号):

I am using System.Linq.Dynamic and have the following simplified structure (model):

父 - >儿童(Child类型集合)

Parent -> Children (Collection of type Child)

孩子有属性 SortingOrder

我想要检索父母列表包括儿童和按排序顺序排序。

I would like retrieve list of Parents include Children and order by Sorting Order.

我可以使用LINQ / C#代码

I can do that with LINQ / C# code

Parents.OrderBy(X => x.Children.OrderBy(Z => z.SortingOrder)。选择(Z => z.SortingOrder).FirstOrDefault())

它可以与EF(6.0)正常工作,但问题是使用字符串的所有动态示例我无法找到从字符串创建相同表达式的解决方案。所以最终应该按照这样排序

It works fine with EF (6.0) but problem is with all dynamic examples using string I cannot find solution to create the same expressions from string. So ultimately it should be sorted like this

Parents.Include(Children)。OrderBy(Children.SortingOrder)

显然,作为Collection的Collection不具有SortingOrder,因此所有示例都将失败。

Obviously Children as collection does not have SortingOrder and therefore all examples fails.

请咨询,找不到解决方案几个小时。我认为解决方案将是创建lambda表达式(x => x.Children.OrderBy(z => z.SortingOrder).Select(z => z.SortingOrder).FirstOrDefault() )动态地,但不知道该怎么做,或任何其他帮助非常感激。

Please advice, could not find solution for hours. I think solution would be in creating that lambda expression (x=>x.Children.OrderBy(z=>z.SortingOrder).Select(z=>z.SortingOrder).FirstOrDefault()) dynamically but not sure how to do that, or any other help greatly appreciated.

我相信它是可行的,因为它的编译强大

I am sure it's doable as it's working as compiled strongly typed expression.

研究的代码示例:

EF:LINQ - 使用带有条件的子集合的顺序 - ArgumentException

如何动态指定Linq OrderBy参数

https://www.simple-talk.com/dotnet/.net-framework/dynamic-linq-queries-with-expression-trees/

http:// www .codeproject.com / Articles / 235860 / Expression-Tree-Basics

推荐答案

没有一般的解决方案。 System.Linq.Dynamic 与正常LINQ相比太有限了 - 许多功能不受支持,不喜欢子集合并且要求您使用支持的集合函数,不再不小于任何计数最小最大 Sum 和Average`。

There is no general solution. System.Linq.Dynamic is too limited compared to "normal" LINQ - many functions are not supported, doesn't like sub collections and requres you to use one of the supported "aggregate" functions, which are no more and no less than Any, Count, Min, Max, Sum and Average`.

但是,您的具体案例有动态LINQ支持的替代解决方案。

However, your specific case has alternative solution which is supported by Dynamic LINQ.

以示例查询为例。

Parents.OrderBy(x => x.Children.OrderBy(z => z.SortingOrder).Select(z => z.SortingOrder).FirstOrDefault())

相当于

Parents.OrderBy(p => p.Children.Min(c => c.SortingOrder))

其中动态LINQ将如下

which with Dynamic LINQ would be like this

Parents.OrderBy("Children.Min(SortingOrder)")

这篇关于通过收集属性排序动态LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆