c# DataTable行转列

/// <summary>
/// datatable行转列
/// </summary>
/// <param name="dtSrc">来源datatable</param>
/// <returns>行转列结束的datatable</returns>
private System.Data.DataTable ConvertDataTable(System.Data.DataTable dt)
{
var date = this.dtpStartDay.Text + "到" + this.dtpEndDay.Text;
var list = from c in dt.AsEnumerable()
select new {
日期 = c.Field<string>("日期"),
财务编号 = c.Field<string>("财务编号"),
财务名称 = c.Field<string>("财务名称"),
平台名称 = c.Field<string>("平台名称"),
面值 = Convert.ToDecimal(c.Field<string>("面值"))
}; var tmplist = (from item in list
group item by item.财务编号 into g
select new
{
code = g.Key,
vallist = from val in g
group val by val.平台名称 into gs
select new
{
pltname = gs.Key,
pltvalue = gs.Sum(t => t.面值)
}
}).ToList(); dt = new System.Data.DataTable();
dt.Columns.Add("日期");
dt.Columns.Add("财务编号");
dt.Columns.Add("财务名称");
var colNames = list.Select(t => t.平台名称).Distinct();
foreach (var col in colNames)
{
dt.Columns.Add(col);
}
dt.Columns.Add("平台合计"); foreach (var item in tmplist)
{
var dr = dt.NewRow(); dr.BeginEdit();
dr["日期"] = date;
dr["财务编号"] = item.code;
dr["财务名称"] = list.FirstOrDefault(t => t.财务编号 == item.code).财务名称;
dr["平台合计"] = item.vallist.Sum(t => t.pltvalue); foreach (var col in colNames)
{
if (item.vallist.Any(t => t.pltname == col))
{
dr[col] = item.vallist.Single(t => t.pltname == col).pltvalue;
}
else
{
dr[col] = 0;
}
} dr.EndEdit();
dt.Rows.Add(dr);
}
return dt;
}

  

上一篇:Apple Watch视频教程(连载)


下一篇:c++标准库中的string常用函数总结《转》