linq如何正确使用GroupBy

本文关键字:GroupBy 何正确 linq | 更新日期: 2023-09-27 18:15:25

我有以下类:

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

我正试着按以下方式对所有的东西进行分组:

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

References中,我想获得所有references的列表,将我分组的每个组加在一起。

linq如何正确使用GroupBy

SelectMany应该能使结果变平。

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();
                        })