如何对带有子属性的集合进行排序? [英] how do I sort a collection with child property?

查看:71
本文介绍了如何对带有子属性的集合进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该根据子字段对父进行排序.

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.

推荐答案

您的问题有些令人困惑,因为首先使用Entity Framework和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?

其次,更重要的是,您说要"sort Parent by Children Names".您想排序哪个孩子的名字?您确实意识到,您无法将一个名称的列表与另一个名称的列表进行比较,并确定哪个名称应该在另一个名称之前?

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有子级CBCD,而父级PB有子级CCCA.排序的结果是,父级PB将在排序后的列表中排在第一位,因为子级CA将用作PB的主要"子级,而CB将会是PB的主要"子级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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆