audiohifi 于 2016.02.29 19:24 提问

c# 数据统计 请问如何实现
``````遇到一个棘手问题，请老师们帮解答一下：
原始的表

统计表

请问用c#如何实现
``````

7个回答

caozhy      2016.02.29 20:44

`````` using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Q239660
{
class Program
{
static void Main(string[] args)
{
string data = @"aaa bb 10 cc 11 dd 12
aaa cc 9 dd 4 bb 2
aaa cc 16 bb 9 dd 8
bbb a1 6 a2 9 a3 8
bbb a2 7 a3 4 a1 6";
string result = string.Join("\r\n", data.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(' ')).SelectMany(x => Enumerable.Range(0, 3).Select(y => new { a = x[0], b = x[y * 2 + 1], c = int.Parse(x[y * 2 + 2]) }))
.GroupBy(x => x.a)
.Select(x => new { a = x.Key, b = x.GroupBy(y => y.b).Select(y => new { b = y.Key, c = y.Sum(z => z.c) }) })
.Select(x => x.a + " " + string.Join(" ", x.b.Select(y => y.b + " " + y.c.ToString()))));
Console.WriteLine(result);
}
}
}

``````
caozhy      2016.03.03 03:18
`````` using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{
public static void Main()
{
string data = @"aaa bb 10 cc 11 dd 12 ee 13
aaa cc 9 dd 4 bb 2 ee 13
aaa cc 16 bb 9 dd 8 ee 13
bbb a1 6 a2 9 a3 8
bbb a2 7 a3 4 a1 6";
string result = string.Join("\r\n", data.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(' ')).SelectMany(x => Enumerable.Range(0, x.Count() / 2).Select(y => new { a = x[0], b = x[y * 2 + 1], c = int.Parse(x[y * 2 + 2]) }))
.GroupBy(x => x.a)
.Select(x => new { a = x.Key + " " + x.Count() + "次", b = x.GroupBy(y => y.b).Select(y => new { b = y.Key, c = y.Sum(z => z.c) }) })
.Select(x => x.a + " " + string.Join(" ", x.b.Select(y => y.b + " " + y.c.ToString()))));
Console.WriteLine(result);
}
}
``````

http://ideone.com/wD40Jy

aaa 12次 bb 21 cc 36 dd 24 ee 39
bbb 6次 a1 12 a2 16 a3 12

caozhy      2016.02.29 20:44

aaa bb 21 cc 36 dd 24
bbb a1 12 a2 16 a3 12
Press any key to continue . . .

audiohifi   2016.03.01 00:54

audiohifi   2016.03.02 22:49

aaa bb 10 cc 11 dd 12 ee 13
aaa cc 9 dd 4 bb 2 ee13
aaa cc 16 bb 9 dd 8 ee13
bbb a1 6 a2 9 a3 8
bbb a2 7 a3 4 a1 6

audiohifi   2016.03.07 02:45

Why_boy01   2016.03.11 20:10

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Q239660
{
class Program
{
static void Main(string[] args)
{
string data = @"aaa bb 10 cc 11 dd 12
aaa cc 9 dd 4 bb 2
aaa cc 16 bb 9 dd 8
bbb a1 6 a2 9 a3 8
bbb a2 7 a3 4 a1 6";
string result = string.Join("\r\n", data.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(' ')).SelectMany(x => Enumerable.Range(0, 3).Select(y => new { a = x[0], b = x[y * 2 + 1], c = int.Parse(x[y * 2 + 2]) }))
.GroupBy(x => x.a)
.Select(x => new { a = x.Key, b = x.GroupBy(y => y.b).Select(y => new { b = y.Key, c = y.Sum(z => z.c) }) })
.Select(x => x.a + " " + string.Join(" ", x.b.Select(y => y.b + " " + y.c.ToString()))));
Console.WriteLine(result);
}
}
}