Night Walker
Night Walker

Reputation: 21260

linq how to GroupBy correctly

I have following class:

class AssembledDTO
{
    int pid,
    int blockId,
    List<string> references
}

I am trying to group by everything in following way:

AssembledParts.GroupBy(entry => new
                        {
                            entry.PID,
                            entry.BlockId
                        }).
                        Select( (key , val)=> new AssembledDTO
                            {
                                BlockId = key.Key.BlockId,
                                PID = key.Key.PID,
                                References = val.
                            }) 

In References I want to get list of all references added together of each group that I grouped by.

How I can do so ?what I miss here ?

Upvotes: 1

Views: 93

Answers (1)

Jarek
Jarek

Reputation: 3379

SelectMany should do the trick to flatten results.

AssembledParts.GroupBy(entry => new
                    {
                        entry.PID,
                        entry.BlockId
                    }).
                    Select(key => new AssembledDTO
                        {
                            BlockId = key.Key.BlockId,
                            PID = key.Key.PID,
                            References = key.SelectMany(v => v.references).ToList();
                        }) 

Upvotes: 2

Related Questions