我在使用C#计算CSV文件中的某些值时遇到问题。
我无法在Google上找到任何相关示例。
61,0000000000005,00000001,1,00002999,00002999,61,00,0,T,006158932
61,0000000000005,00000001,1,00002999,00002999,30,00,0,T,014026734
61,0000000000030,00000001,1,00003499,00003499,29,01,0,T,009033154
61,0000000000049,00000001,1,00002999,00002999,30,01,0,T,014026574
61,0000000000049,00000003,1,00002999,00008997,05,01,0,T,008111854
61,0000000000049,00000001,1,00002999,00002999,03,01,0,T,004211647
61,0000000000049,00000001,1,00002999,00002999,11,01,0,T,001058055
61,0000000000056,00000002,1,00000999,00001998,30,01,0,T,014026627
61,0000000000056,00000001,1,00000999,00000999,30,01,0,T,014026627
61,0000000000056,00000001,1,00000999,00000999,05,01,0,T,008111875
61,0000000000056,00000001,1,00000999,00000999,03,01,0,T,004211642
61,0000000000056,00000001,1,00000999,00000999,06,01,0,T,011133513
61,0000000000058,00000001,1,00001499,00001499,30,01,0,T,014026652
61,0000000000058,00000001,1,00001499,00001499,11,01,0,T,001057984
61,0000000000058,00000001,1,00001499,00001499,11,01,0,T,001058068
61,0000000000058,00000001,1,00001499,00001499,11,01,0,T,001058068
61,0000000000058,00000001,1,00001499,00001499,16,01,0,T,003205784
61,0000000000058,00000001,1,00001499,00001499,16,01,0,T,003205784
上面的文件按第2列排序,我需要添加第3列的值以及第6列的值,
如果我采用上面给出的数据,我需要将其分解如下,然后进行计算
输出中的第一列不会一起添加,因为这是一个标识符。然后必须将第3列中的所有值加在一起,然后在第6列中添加所有值,以获得如下所示的输出
0000000000005 00000002 00005998
0000000000030 00000001 00003499
0000000000049 00000006 00017994
0000000000056 00000006 00005994
0000000000058 00000006 00008994
我可以从哪里开始?
答案 0 :(得分:3)
您可以使用GroupBy
和Sum
:
List<string> allCsvLines = .... (fill it)
var result = allCsvLines.Select(line => line.Split(','))
.Where(arr => arr.Length >= 11)
.Select(arr => new { Col2 = int.Parse(arr[1]), Col3 = int.Parse(arr[2]), Col6 = int.Parse(arr[5]), arr })
.GroupBy(x => x.Col2)
.Select(g => new { Col2 = g.Key, Col3 = g.Sum(x => x.Col3), Col6 = g.Sum(x => x.Col6) });