如何使用 LINQ 对集合及其子集合进行排序?
我有一组员工,每个员工都有一组职责。我想输出按姓名排序的员工列表,并输出按职务排序的他们的职责。
因此,它应该这样输出:
Jane Jones
职责:
职责 A
职责 B
迈克史密斯
职责:
职责 A
职责 C
要获取我使用的初始集合:
var employees = _context.Employees.OrderBy(e => e.Name);
但我似乎也不知道如何订购职责子集合。
我正在使用 MVC,并且我的视图接收强类型的 Employee 集合,因此我不想构建并返回匿名类型。
I have a collection of Employees, and each employee has a collection of Responsibilities. I would like to output a list of the employees sorted by Name and output their Responsibilities, sorted by Title.
So, it should be outputted like this:
Jane Jones
Responsibilities:
Responsibility A
Responsibility B
Mike Smith
Responsibilities:
Responsibility A
Responsibility C
To get the initial collection I use:
var employees = _context.Employees.OrderBy(e => e.Name);
but I can't seem to figure out how to order the Responsibilities subcollection as well.
I'm using MVC and my View receives a strongly typed Employee collection so I don't want to build and return an anonymous type.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以这样做:
You could do something like:
第一种方法:(仅适用于职责定义为 IList 的 LINQ to 对象)
您可以复制到新的员工集合中,但这意味着您需要重新复制每个字段都包含在新员工中,如下所示:
第二种方法:
使用数据加载选项。基本上,您创建一个 DataLoadOptions 对象,它指定如何对特定关系进行排序,因此在您的情况下:
将自动对职责进行排序。
1st approach: (is only suitable for LINQ to Objects with Responsibilities defined as IList)
You could copy into a new collection of Employees but this means that you need to re-copy each field into new employee, something like this:
2nd approach:
Using the DataLoadOptions. Basically, you create a DataLoadOptions object which specifies how to order a particular relationship, so in your case:
The Responsibilities will be ordered automatically.