Sorting Dynamic LINQ By Collection Property

柔情痞子 提交于 2019-12-11 10:37:23

问题


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

Parent -> Children (Collection of type Child)

Child has property SortingOrder

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

I can do that with LINQ / C# code

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

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

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

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.

Examples of code researched:

  • how do I sort a collection with child property?

  • EF: LINQ - orderby using child collection with condition - ArgumentException

  • How do I specify the Linq OrderBy argument dynamically?

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

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


回答1:


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`.

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

Let take your sample query as example.

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

is equivalent to

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

which with Dynamic LINQ would be like this

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


来源:https://stackoverflow.com/questions/35496303/sorting-dynamic-linq-by-collection-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!