C#用DataTable實現Group by資料統計
C#用DataTable實現Group by資料統計
資料來源:https://www.796t.com/p/615724.html
code
using System;
using System.Collections.Generic;
using System.Data;
public class Example
{
public static void Main()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("name", typeof(string)),
new DataColumn("sex", typeof(string)),
new DataColumn("score", typeof(int)) });
dt.Rows.Add(new object[] { "张三", "男", 1 });
dt.Rows.Add(new object[] { "张三", "男", 4 });
dt.Rows.Add(new object[] { "李四", "男", 100 });
dt.Rows.Add(new object[] { "李四", "女", 90 });
dt.Rows.Add(new object[] { "王五", "女", 77 });
DataTable dtResult = dt.Clone();
DataTable dtName = dt.DefaultView.ToTable(true, "name", "sex");
for (int i = 0; i < dtName.Rows.Count; i++)
{
DataRow[] rows = dt.Select("name='" + dtName.Rows[i][0] + "' and sex='" + dtName.Rows[i][1] + "'");
//temp用来存储筛选出来的数据
DataTable temp = dtResult.Clone();
foreach (DataRow row in rows)
{
temp.Rows.Add(row.ItemArray);
}
DataRow dr = dtResult.NewRow();
dr[0] = dtName.Rows[i][0].ToString();
dr[1] = temp.Compute("sum(score)", "");
dtResult.Rows.Add(dr);
}
}
}