Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order parent object list by child list attribute

I want to sort an object list in C# by LINQ, I want to order this list by a child list with a certain attribute: The class structure based on nhibernate, all Attributes are public virtual.

ParentobjectsList.OrderBy(x => x.ChildobjectList.Attribute);

How can I achive this.

like image 820
Higune Avatar asked Jun 15 '13 15:06

Higune


Video Answer


1 Answers

It sounds like your structure is something like this:

class ChildObject
{
    public int Attribute { get; set; }
}

class ParentObject
{
    public IEnumerable<ChildObject> ChildobjectList { get; set; }
}

In this case it's not possible to simply order an IEnumerable<ParentObject> by the ChildObject.Attribute property, because there are potentially many values for each ParentObject. How is Linq going to know which value to use for the ordering? You'll have to use some kind of aggregate function. There are many options, but here are just a few:

  • Max to sort by the largest element in ChildobjectList
  • Min to sort by the smallest element in ChildobjectList
  • First to sort by the first item in the ChildobjectList
  • Sum to sort by the sum of values, assuming the type of Attribute can be summed

Precisely which one you use depends on your exact requirements. In any case you'll use it like this:

var result = 
    ParentobjectsList.OrderBy(x => x.ChildobjectList.Max(c => c.Attribute));
like image 68
p.s.w.g Avatar answered Sep 28 '22 13:09

p.s.w.g