简体   繁体   English

按子列表属性排序父对象列表

[英]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. 我想通过LINQ对C#中的对象列表进行排序,我想通过具有特定属性的子列表来排序此列表:基于nhibernate的类结构,所有属性都是公共虚拟的。

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 . 在这种情况下,不可能简单地通过ChildObject.Attribute属性对IEnumerable<ParentObject>进行ChildObject.Attribute ,因为每个ParentObject可能有很多值。 How is Linq going to know which value to use for the ordering? Linq如何知道订购使用哪个值? 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 MaxChildobjectList的最大元素ChildobjectList
  • Min to sort by the smallest element in ChildobjectList MinChildobjectList的最小元素ChildobjectList
  • First to sort by the first item in the ChildobjectList FirstChildobjectList的第一项排序
  • Sum to sort by the sum of values, assuming the type of Attribute can be summed 如果可以求和Attribute的类型,则按值的Sum进行排序

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));
var sortedList = ParentobjectsList.OrderBy(x => x.ChildobjectList.Attribute);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM