LINQ Query - how sort and filter on eager fetch

前端 未结 3 1730
粉色の甜心
粉色の甜心 2020-12-20 05:03

How do I do a eager query of a parent child relationship that:

  1. filters a on child fields
  2. sorts on both parent and child
  3. return a List or Par
3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-20 05:35

    The solution depends on what exactly you are trying to do.

    The first query gives the impression that you want to "flatten out" the results in objects, like this (pseudocode, I hope it's clear what I mean):

    { Parent1, Child1 }
    { Parent1, Child2 }
    { Parent1, Child3 }
    { Parent2, Child1 }
    

    In this case each result "row" would be an object having a Parent and a Child property, and you could sort by parent name and then by child name.

    The second query just returns the Parent objects and (you don't show it but I assume EF has been instructed to do that) each one has a Children collection. In this case you can only sort by parent name; if you want to sort each Parent's children, sort the Children collection on that object by itself.

    Which of the two do you want to do?

    Update

    OK, it seems you want the second one. I don't believe it can be done directly. You can just do it when you enumerate the results - since the Parents are already sorted, simply sort each one's children:

    var sortedChildren = parent.Children.OrderBy(c => c.Name);
    

提交回复
热议问题