简体   繁体   中英

LINQ query grouping by column in child table and ordering the results within the groups

I have two tables: Resources and 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. 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 ?

Note that the CategorisedResources property of the model is currently of type:

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:

model.CategorisedResources = _db.Resources.GroupBy(r => 
    r.ResourceCategory.Name, (catName, catRes) => catRes.OrderBy(cr => cr.DisplayText));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM