我有以下课程:
public class File
{ public string FileId;
public <Batch> Batches;
public decimal Amount;
}
public class Batch
{ public string FileId;
public string BatchCode;
public decimal Amount;
}
我想创建以下输出对象:
public class SummaryFile
{
public List<File> Files;
}
现在我有以下Batch类列表:
List<Batch> batches;
现在这个列表如下所示:
batches[0] = new Batch{ FileId = 1, BatchCode = "A", Amount = 5 };
batches[1] = new Batch{ FileId = 1, BatchCode = "B", Amount = 10 };
batches[2] = new Batch{ FileId = 2, BatchCode = "C", Amount = 22 };
我的输出对象如下:
public class SummaryFile
{
public List<File> Files;
}
我希望我的输出看起来如下:
"Files": [
{
"FileId": "1",
"Batches": [
{
"BatchCode": "A",
"Amount": 5
},
{
"BatchCode": "B",
"Amount": 10
},
],
"FileAmount": 15,
},
{
"FileId": "2",
"Batches": [
{
"BatchCode": "C",
"Amount": 22
},
],
"FileAmount": 22
}
]
是否有可能使用Linq实现这一目标,如果不是最好的方法是什么?来自大型机,我将使用控制中断处理来完成此任务。谢谢你的帮助。
答案 0 :(得分:1)
var summaryFile = new SummaryFile
{
Files = batches.GroupBy(p => p.FileId)
.Select(p => new File
{
FileId = p.Key,
Batches = p.ToList(),
Amount = p.Sum(x => x.Amount)
}).ToList()
};