如何使用LINQ对集合及其子集合进行排序? [英] How to order a collection and its subcollection using LINQ?
问题描述
我有一个员工集合,每个员工都有一个职责集合。
因此,应输出如下:
<琼>
职责:
责任A
责任B
Mike Smith
职责:
责任A
责任C
要使用初始集合,我使用:
var employees = _context.Employees.OrderBy(e => e.Name);
但我似乎不知道如何订购责任子集合。
我正在使用MVC,我的View收到一个强类型的Employee集合,所以我不想构建和返回一个匿名类型。
您可以这样做:
= _context.Employees.OrderBy(e => e.Name);
employees.ToList()。ForEach(e => e.Responsibilities = e.Responsibilities.OrderBy(r => r.Name));
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.
You could do something like:
var employees = _context.Employees.OrderBy(e => e.Name);
employees.ToList().ForEach(e => e.Responsibilities = e.Responsibilities.OrderBy(r => r.Name));
这篇关于如何使用LINQ对集合及其子集合进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!