Linq DataTable Group By 分组显示人员明细

实现功能:

     Linq DataTable Group By 分组显示人员明细

多个字段分组源码样例:

原始数据:

Linq DataTable Group By 分组显示人员明细

分组后的输出结果:

Linq DataTable Group By 分组显示人员明细

源代码:

         public static void PrintPersons()
{
//准备数据
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(int)));
dt.Columns.Add(new DataColumn("UserName", typeof(string)));
dt.Columns.Add(new DataColumn("DeptNo", typeof(string)));
dt.Columns.Add(new DataColumn("DeptName", typeof(string)));
DataRow drTemp = null;
for (int i = ; i <= ; i++)
{
drTemp = dt.NewRow();
drTemp["ID"] = i;
drTemp["UserName"] = "姓名" + i.ToString(); if (i < )
{
drTemp["DeptNo"] = "";
drTemp["DeptName"] = "人事部";
}
else
{
drTemp["DeptNo"] = "";
drTemp["DeptName"] = "生产部";
}
dt.Rows.Add(drTemp);
} Console.WriteLine("分组前:");
foreach (DataRow row in dt.Rows)
{
Console.WriteLine(string.Format("{0} {1} {2} {3} ", row.ItemArray));
}
Console.WriteLine(""); Console.WriteLine("分组后:"); //Linq分组查询,并按分组显示人员明细
var query = from g in dt.AsEnumerable()
group g by new { t1 = g.Field<string>("DeptNo"), t2 = g.Field<string>("DeptName") } into companys
select new { DeptNo = companys.Key.t1, DeptName = companys.Key.t2, StallInfo = companys }; foreach (var userInfo in query)
{
System.Collections.Generic.List<DataRow> dataRows = userInfo.StallInfo.ToList(); Console.WriteLine(string.Format("{0}({1})人员名单: ", userInfo.DeptName, userInfo.DeptNo));
foreach (System.Data.DataRow dr in dataRows)
{
Console.WriteLine(string.Format("{0} {1} ", dr.ItemArray));
}
}
Console.ReadLine();
}
上一篇:DataTable Group By或运算 Linq Aggregate的使用


下一篇:环境搭建二 secureCRT配置