[英]LINQ query grouping by column in child table and ordering the results within the groups
I have two tables: Resources and ResourceCategories. 我有两个表:Resources和ResourceCategories。 For the sake of this question they can simply have the following structures: 为了这个问题,他们可以简单地具有以下结构:
Resource 资源资源
public long Id { get; set; }
public string DisplayText { get; set; }
public long CategoryId { get; set; }
public virtual ResourceCategory ResourceCategory { get; set; }
ResourceCategory 资源类别
public long Id { get; set; }
public string Name { get; set; }
I want to return a list of resources grouped by resource category Name
and ordered by resource DisplayText
within each group. 我想返回按资源类别Name
分组并按每个组内的资源DisplayText
排序的资源列表。 I can easily get the grouping working but I cannot work out the ordering. 我可以轻松地进行分组工作,但无法进行排序。
I basically want: 我基本上想要:
Resource Category 1
Resource A
Resource D
Resource K
Resource Category 2
Resource C
Resource F
Resource M
...
The code for the grouping is very simple: 分组的代码非常简单:
model.CategorisedResources = _db.Resources
.GroupBy(r => r.ResourceCategory.Name);
How can I achieve the ordering of each group by the resource DisplayText
? 如何通过资源DisplayText
实现每个组的排序?
Note that the CategorisedResources
property of the model is currently of type: 请注意,模型的CategorisedResources
属性当前为类型:
IEnumerable<IGrouping<string, Resource>>
but that possibly could be changed, if necessary. 但如有必要,可以更改。
You can achieve this by first Sort your list and then Group them 您可以通过首先对列表进行排序,然后对它们进行分组来实现此目的
_db.Resources
.OrderBy(r=>r.DisplayText).ToList()
.GroupBy(r => r.ResourceCategory.Name);
In order to specify the sort order within a group, you can specify the resultSelector
argument to the GroupBy
method: 为了指定组内的排序顺序,可以为GroupBy
方法指定resultSelector
参数:
model.CategorisedResources = _db.Resources.GroupBy(r =>
r.ResourceCategory.Name, (catName, catRes) => catRes.OrderBy(cr => cr.DisplayText));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.