'LINQ Group By and merge properties

private static void Main()
{
    var accounts = new List<Account>()
    {
    new Account { PrimaryId = 1, SecondaryId = 10 },
    new Account { PrimaryId = 1, SecondaryId = 12 }
    };
}

public class Account
{
    public int PrimaryId { get; set; }
    public IList<int> SecondaryIds { get; set; }
    public int SecondaryId { get; set; }
}

Suppose I have the above code, I would like to group by PrimaryId and merge SecondaryId into SecondaryIds.

For example:

// PrimaryId = 1
// SecondaryIds = 10, 12

How can achieve it?

I did this so far

var rs = accounts.GroupBy(g => g.PrimaryId == 1)
.Select(s => new Accounts 
{ PrimaryId = 1, SecondaryIds = new List<int>() { /*???*/  } });


Solution 1:[1]

When using .GroupBy() followed by .Select(), you need to drill down one level inside your grouped items:

var rs = accounts
    .GroupBy(a => a.PrimaryId)
    .Select(gr => new Account {
        PrimaryId = gr.Key,
        SecondaryIds = gr.Select(account => account.SecondaryId).ToList()
    });

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