Sort child objects while selecting the parent using LINQ

Imagine you've got some Entity Framework entities that look like this (obviously not these specific classes, but the autogenerated ones with all the Entity Framework plumbing; these are just for illustration):

public class Parent
{
    public int ID { get; set; }
    public List<Child> Children { get; set; }
}

public class Child
{
    public int ID { get; set; }
    public Parent Parent { get; set; }
    public int Number { get; set; }
}

I have a LINQ query that looks like this:

from parent in context.Parents.Include("Child")
select parent

However, this returns a list of Parents where the children are in ID order. I want the children to be sorted by their Number property within their Parent. How can this be done?

Edit: A clarification: the idea is to have the query hidden behind a method call (in the layer facade) that simply returns an IList<Parent> . This makes using solutions like anonymous class queries and manual sorting painful (compared to some panacea solution where you can just do it in the query or something).


Alex James discusses this issue in this tip.

Essentially, relationships are considered as unordered, per standard relational modeling. So you can't get them sorted. But you can project onto other collections, which can be sorted.


Take a look at this post. You could try something like this:

var query = ((from parent in context.Parents
              from child in parent.Child
              orderby child.Number ascending
              select parent) as ObjectQuery<Parent>
            ).Include("Child");

One option is executing the query and sorting in memory (eg on output).

var parents = context.Parents.Include("Child").ToList(); //note that ToList is here just to execute the query and get the objects in memory

foreach (var p in parents)
{
   //do something with parent item
   foreach (var c in p.Child.OrderBy(c => c.Number))
   {
      /do something with the child item
   }
}

There are two other options that also seem to work with their own pros and cons:

LINQ ".Include" orderby in subquery

LINQ OrderBy Name ThenBy ChildrenCollection.Name

链接地址: http://www.djcxy.com/p/6420.html

上一篇: 按属性排序自定义对象的ArrayList

下一篇: 使用LINQ选择父对象时排序子对象