Scott
Scott

Reputation: 13931

LINQ group list and combine collections

Given these classes:

public class Employee
{
  public int EmployeeId { get; set; }
  public int GroupId { get; set; }
  public List<Plans> Plans { get; set; }
}

public class Plan
{
 public int PlanYearId { get; set; }
 public string Name { get; set; }
}

And given a setup like so:

var employees = new List<Employee> {
    new Employee {
        EmployeeId = 1,
        GroupId = 1,
        Plans = new List<Plan> {
            new Plan {
                PlanReferenceId = 1111,
                Name = "Benefit 1"
            }}};
    new Employee {
        EmployeeId = 1,
        GroupId = 1,
        Plans = new List<Plan> {
            new Plan {
                PlanReferenceId= 2222,
                Name = "Benefit 2"
            },
            new Plan {
                PlanReferenceId= 2222,
                Name = "Benefit 3"
            }}}};   

How can I use LINQ to group these employees by both EmployeeId and GroupId and then combine the two List<Plan> properties so that i would end up with something like this:

var employee = new Employee
{
    EmployeeId = 1,
    GroupId = 1,
    Plans = new List<Plan> {
        new Plan {
            PlanReferenceId = 1111,
            Name = "Benefit 1"
        },
        new Plan {
            PlanReferenceId = 2222,
            Name = "Benefit 2"
        },
        new Plan {
            PlanReferenceId = 2222,
            Name = "Benefit 3"
        }
    }
}

Upvotes: 1

Views: 324

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205719

Just use combination of GroupBy and SelectMany:

var result = employees
    .GroupBy(e => new { e.EmployeeId, e.GroupId })
    .Select(g => new Employee
    {
        EmployeeId = g.Key.EmployeeId,
        GroupId = g.Key.GroupId,
        Plans = g.SelectMany(e => e.Plans).ToList()
    }).ToList();

Upvotes: 3

Related Questions