dotnet / dotnet/efcore

Translate SelectMany over GroupBy to flatten the elements back

Open
#36,510 0 comments 1 reaction 0 assignees View on GitHub
area-query
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

SelectMany can be used to flatten a sequence of groupings back, effectively undoing the GroupBy:

```c#
_ = await context.Employees
.GroupBy(e => e.Department)
.SelectMany(g => g)
.ToListAsync();
```

In itself, this isn't very useful. However, it can allow a transformation to be applied to the elements which takes the group into account, and can thus allow representing SQL window functions:

```c#
_ = await context.Employees
.GroupBy(e => e.Department)
.SelectMany(g => g.Select(e => new
{
e.Id, e.Name,
e.Salary,
SalaryPercentage = e.Salary / g.Sum(e => e.Salary)
}))
.ToListAsync();
```

This returns a flat list of employees, where each employee is augmented with a column containing the percentage their salary takes within their department.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.