8,497
社区成员
发帖
与我相关
我的任务
分享
DataTable dt= new DataTable();
dt.Columns.Add("c1", typeof(int));
dt.Columns.Add("c2", typeof(string));
dt.Columns.Add("c3", typeof(int));
dt.Rows.Add(1, "技术部", 130, 10);
dt.Rows.Add(2, "产品部", 200, 20);
dt.Rows.Add(3, "市场部", 130, 30);
dt.Rows.Add(3, "市场部", 30, 30);
dt.Rows.Cast<DataRow>().GroupBy<DataRow, string>(row => Convert.ToString(row["c2"])).Select(group => new { group.Key, Value = group.Sum(x => Convert.ToInt32(x["c3"])) });
static DataTable Test() {
DataTable dt = new DataTable();
dt.Columns.Add("c1", typeof(int));
dt.Columns.Add("c2", typeof(string));
dt.Columns.Add("c3", typeof(int));
dt.Columns.Add("c4", typeof(int));
dt.Rows.Add(1, "技术部", 130, 10);
dt.Rows.Add(2, "产品部", 200, 20);
dt.Rows.Add(3, "市场部", 130, 30);
dt.Rows.Add(3, "市场部", 30, 30);
var r = dt.GroupBy(new ColSets[] { "c2" }, "SUM(Child.c3)");
return r;
}
static void Main()
{
DataTable dt = new DataTable();
dt.Columns.Add("c1", typeof(int));
dt.Columns.Add("c2", typeof(string));
dt.Columns.Add("c3", typeof(int));
dt.Rows.Add(1, "技术部", 130);
dt.Rows.Add(2, "产品部", 200);
dt.Rows.Add(3, "市场部", 130);
dt.Rows.Add(3, "市场部", 30);
var query = from d in dt.AsEnumerable()
group d by d.Field<string>("c2") into g
select new
{
c2 = g.Key,
c3 = g.Sum(t => t.Field<int>("c3"))
};
query.ToList().ForEach(q => Console.WriteLine("{0},{1}", q.c2, q.c3));
}
DataTable dt= new DataTable();
dt.Columns.Add("c1", typeof(int));
dt.Columns.Add("c2", typeof(string));
dt.Columns.Add("c3", typeof(int));
dt.Columns.Add("c4", typeof(int));
dt.Rows.Add(1, "技术部", 130, 10);
dt.Rows.Add(2, "产品部", 200, 20);
dt.Rows.Add(3, "市场部", 130, 30);
dt.Rows.Add(3, "市场部", 30, 30);
IEnumerable<IGrouping<string, DataRow>> result = dt.Rows.Cast<DataRow>().GroupBy<DataRow, string>(r=>r.Field<string>("c2"));
foreach (IGrouping<string, DataRow> ig in result)
{
Console.Write(ig.Key + ":");
Console.WriteLine(ig.Sum(r=>r.Field<int>("c3")));
}
void Main()
{
DataTable dt= new DataTable();
dt.Columns.Add("c1", typeof(int));
dt.Columns.Add("c2", typeof(string));
dt.Columns.Add("c3", typeof(int));
dt.Rows.Add(1, "技术部", 130);
dt.Rows.Add(2, "产品部", 200);
dt.Rows.Add(3, "市场部", 130);
dt.Rows.Add(3, "市场部", 30);
var query= dt.AsEnumerable().GroupBy(t=>t.Field<int>("c1"))
.Select(g=>new {
c1=g.Key,
c2=g.First().Field<string>("c2"),
c3=g.Sum(m=>m.Field<int>("c3"))
});
DataTable dtResult=dt.Clone();
query.ToList().ForEach(q=>dtResult.Rows.Add(q.c1,q.c2,q.c3));
}