如何对具有子属性的集合进行排序? [英] how do I sort a collection with child property?
问题描述
我应该根据孩子的领域对父母进行排序.
I should sort parent based on a field of child.
示例代码;
IQueryable<Parent> data = context.Parents.Include(o=>o.Children);
//孩子有一个成员(字符串)名称.
//Child has a member (string) Name.
问题:如何按孩子的名字对父母进行排序.
question: how can I sort Parent by Children Names.
推荐答案
您的问题有点令人困惑,因为首先,它同时标记了实体框架和 LINQ-to-SQL.您实际使用的是哪种 ORM?
Your question is somewhat confusing, since first of all, it is tagged both with Entity Framework and LINQ-to-SQL. Which ORM are your actually using?
其次,更重要的是,您说您想要按子项名称对父项进行排序"
.您想按哪个孩子的名字排序?您确实意识到您无法将一个列表名称与另一个列表名称进行比较并决定哪个应该在另一个之前?
Secondly, and more to the point, you say that you want to "sort Parent by Children Names"
. Which child name do you want to sort by? You do realize that you can't compare a list of names to another list of names and decide which one should come before the other?
因此,如果我假设您想按字典序排在第一位的子名称进行排序,那么您的解决方案将如下(@Paul 对此很接近,但您需要指定要排序的属性):>
So if I assume you want to sort by the child name that comes first lexicographically, your solution would be the following (@Paul was close on this one, but you need to specify the property you are sorting by):
context.
Parents.
OrderBy(p => p.
Children.
OrderBy(c => c.Name).Select(c => c.Name).FirstOrDefault()
);
在这种情况下,请考虑以下设置.父 PA
有子 CB
和 CD
而父 PB
有子 CC
和 <代码>CA.作为排序的结果,父 PB
将在排序列表中排在第一位,因为子 CA
将用作 PB的主要"子节点code>,而
CB
将是 PA
的主要"子级.如果这不是您要找的行为,请提供示例和更清晰的描述.
In this case, consider the following setup. Parent PA
has children CB
and CD
while parent PB
has children CC
and CA
. As a result of the sorting, parent PB
will come first in the sorted list, since child CA
will be used as the "main" child for PB
, while CB
will be the "main" child for PA
. If that's not the behavior you are looking for, please provide an example and a clearer description.
这篇关于如何对具有子属性的集合进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!