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

时间:2024-07-07 18:07:08

实现功能:

     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();
}