'LINQ Group with nested list

I'm trying to group my data using LINQ. This is the model I use:

public class Employee
{
   public string FirstName {get;set;}
   public string LastName {get;set;}
   public IEnumerable<string> Groups {get;set;}
}

And I have the IEnumerable<Employees> and I want to transform this:

FirstName=TestName1, SecondName=TestName1, Groups { Group1, Group2 },
FirstName=TestName2, SecondName=TestName2, Groups { Group1, Group3 }
...

To this:

Key=Group1,
Values:
{
   FirstName=TestName1, SecondName=TestName1, Groups { Group1, Group2 };
   FirstName=TestName2, SecondName=TestName2, Groups { Group1, Group3 };
};
Key=Group2,
Values:
{
   FirstName=TestName1, SecondName=TestName1, Groups { Group1, Group2 };
};
...

So, I need to somehow revert grouping from 'grouping' Groups by Employee, to grouping Employees by Group. I've tried to use GroupJoin Employees with Groups (extracted them by employee.SelectMany(e => e.Groups).Distinct();), but my queries don't work. Could someone help me please?



Solution 1:[1]

You could alternatively identify the groups first and then create a dictionary.

var groups = employees
    .SelectMany(e => e.Groups)
    .Distinct();

var employeesByGroup = groups
    .ToDictionary(
        group => group,
        group => employees
            .Where(e => e.Groups.Contains(group)));

Note: As commented below, this will iterate over the source list multiple times, which may cause performance issues if employees is large.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1