audiohifi 于 2016.03.22 22:38 提问

caozhy老师，还的请您帮我看看分组统计的问题
``````您上次的回答帮我解决了绝大部分问题，无奈分组统计这里，还需要您点化一下，多谢
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"

8个回答

caozhy      2016.03.24 14:37

``````using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
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";
var r1 = data.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(' '));
var result = r1.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 + " " + r1.Where(y => y[0] == x.Key).Count() + "次", b = x.GroupBy(y => y.b).Select(y => new { b = y.Key, c = y.Sum(z => z.c) }) });
DataTable dt = new DataTable();
for (int i = 0; i < 10; i++)
foreach (var item in result)
{
var row = dt.NewRow();
row[0] = item.a;
int j = 1;
foreach (var item1 in item.b)
{
row[j++] = item1.b;
row[j++] = item1.c;
}
}
DataGridView dgv = new DataGridView();
dgv.Dock = DockStyle.Fill;
dgv.DataSource = dt;
}
}
}

``````
caozhy      2016.03.22 22:58

audiohifi   2016.03.22 23:40

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";
var result = 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) }) });
DataTable dt = new DataTable();
for (int i = 0; i < 10; i++)
foreach (var item in result)
{
var row = dt.NewRow();
row[0] = item.a;
int j = 1;
foreach (var item1 in item.b)
{
row[j++] = item1.b;
row[j++] = item1.c;
}
}
DataGridView dgv = new DataGridView();
dgv.Dock = DockStyle.Fill;
dgv.DataSource = dt;

herozhangbz 说好的c#呢，又是拉姆达又是js的好高大上。。。其实没那么麻烦的

audiohifi   2016.03.23 00:02

herozhangbz   2016.03.23 10:55

`````` Dictionary<string , int> d = new Dictionary<string , int>();
string str = "Welcome to ChinaWorld";
string[] cs = str.Split(' ');
for (int i = 0; i < cs.Length; i++)
{
if (d.ContainsKey(cs[i]))
d[cs[i]]++;
else
d[cs[i]] = 1;
}
foreach (KeyValuePair<string, int> kv in d)
Console.WriteLine("字符{0}出现{1}次", kv.Key, kv.Value);

``````

enpterexpress   2016.03.23 10:58
audiohifi   2016.03.24 02:35

caozhy 不好意思，才看到。我写了一个给你。不过貌似你已经解决了。

audiohifi   2016.03.24 22:41