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.
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 summedPrecisely 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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With