如何使用lambda表达式或任何其他逻辑转换数据
本文关键字:转换 数据 其他 任何 何使用 lambda 表达式 | 更新日期: 2023-09-27 17:59:17
我有一个DataTable,它包含这种格式的数据。我想把它转换成另一种格式。实现这一点最简单的方法是什么?可能使用lambda表达式。我正在使用C#4.0
dattable1:
seq id Amt
=============================
1 00782 10
2 00782 20
3 00782 30
1 003850 40
2 003850 50
3 003850 60
1 005723 70
2 005723 80
3 005723 90
To be stored in another datatable or list in this format
1 00782 003850 005723 10 40 70
2 00782 003850 005723 20 50 80
3 00782 003850 005723 30 60 90
示例2
dattable1:
seq id Amt
=============================
1 00782 10
1 003850 40
1 005723 70
To be stored in another datatable or list in this format
1 00782 003850 005723 10 40 70
这将生成符合您要求的输入。
var datatable1 = new[]
{
new { seq = 1, id = "00782", Amt = 10 },
new { seq = 2, id = "00782", Amt = 20 },
new { seq = 3, id = "00782", Amt = 30 },
new { seq = 1, id = "003850", Amt = 40 },
new { seq = 2, id = "003850", Amt = 50 },
new { seq = 3, id = "003850", Amt = 60 },
new { seq = 1, id = "005723", Amt = 70 },
new { seq = 2, id = "005723", Amt = 80 },
new { seq = 3, id = "005723", Amt = 90 }
};
var result = datatable1
.GroupBy(arg => arg.seq)
.Select(arg =>
new
{
arg.Key,
id1 = "00782",
id2 = "003850",
id3 = "005723",
Amt1 = arg.Where(x => x.id == "00782").Sum(x => x.Amt),
Amt2 = arg.Where(x => x.id == "003850").Sum(x => x.Amt),
Amt3 = arg.Where(x => x.id == "005723").Sum(x => x.Amt),
})
.ToList();
[编辑]
对于"所有场景":
var result = datatable1
.GroupBy(arg => arg.seq)
.Select(arg =>
new
{
arg.Key,
Ids = arg.Select(x => x.id).ToList(),
Amounts = arg.Select(x => x.Amt).ToList(),
})
.ToList();
foreach (var row in result)
Console.WriteLine("{0}'t{1}'t{2}", row.Key, string.Join("'t", row.Ids), string.Join("'t", row.Amounts));
输出:
1 00782 003850 005723 10 40 70
2 00782 003850 005723 20 50 80
3 00782 003850 005723 30 60 90