如何展开对象列表?

How to unflatten a list of objects?

我正在尝试将对象转换为 dto

public class topology
{
    public int a { get; set; } 
    public int b { get; set; }
}

public class topologyDto
{
    public int a { get; set; }
    public List<int> b { get; set; }
}

我现在拥有的映射不能将其转换为列表:

public IEnumerable<topologyDto> GetTopology()
{
     return _dataProvider.GetTopology()
     .Select(x => new topologyDto
     {
        a= x.a,
        b= x.b
     };
}

测试集看起来像这样,我想在其中映射到 topologyDto:

var data = new []
{
    new topology() { a = 1, b = 1 },
    new topology() { a = 1, b = 2 },
    new topology() { a = 1, b = 3 },
    new topology() { a = 1, b = 4 },
    new topology() { a = 2, b = 1 },
    new topology() { a = 2, b = 2 },
    new topology() { a = 2, b = 3 },
    new topology() { a = 2, b = 4 },
};

var test = new []
{
    new topologyDto() { a = 1, b = new List<int>() { 1, 2, 3, 4 }, },
    new topologyDto() { a = 2, b = new List<int>() { 1, 2, 3, 4 }, },
}

您似乎想按 a:

分组
_dataProvider.GetTopology()
    .GroupBy(x => x.a)
    .Select(g => new topologyDto
        {
            a = g.Key,
            b = g.Select(t => t.b).ToList(),
        } );