datatable使用lambda
Lamdba是延迟执行的,实际上什么都没有发生,当真正使用对象的时候(例如调用:First, Single, ToList….的时候)才执行。 1.Where var var_dtTable = dtTable.AsEnumerable().Where<DataRow>(W => W["NAME"].ToString()=="张三"); int count = var_dtTable.Count<DataRow>();//获取dtTable中NAME为张三的个数 2.Average //获取dtTable中avg_name列的平局数 int avg = dtTable.AsEnumerable().Average<DataRow>(A => float.Parse(A["avg_name"].ToString())) 3.GroupBy DataTable dtTable = new DataTable();//数据源 DataTable dtResult = new DataTable(); dtResult.Columns.Add("groupBy_name", typeof(string)); dtResult.Columns.Add("sum_name", typeof(int)); dtResult.Columns.Add("count_name", typeof(int)); var var_dtTable= dtTable.AsEnumerable().GroupBy(G => G["groupBy_name"].ToString()).Select(S => new { groupBy_name= s.Key,//获取分组的值 sum_name= s.Sum(m => m.Field<int>("sum_name")),//获取列名为sum_name数据的和 count_name= s.Count(m => m.Field<int>("count_name"))//获取列名为count_name数据的个数 }); var_dtTable.ToList().ForEach(f=> dtResult.Rows.Add(f.groupBy_name,f.sum_name,f.count_name);//对应的顺序为dtResult列的顺序 4.OrderBy DataTable dtTable = new DataTable();//数据源 dtTable = dtTable.AsEnumerable().OrderByDescending(o => o["OrderBy_name"]).CopyToDataTable();//降序 dtTable = dtTable.AsEnumerable().OrderBy(o => o["OrderBy_name"]).CopyToDataTable();//升序 5.Distinct DataTable dtTable = new DataTable();//数据源 //column_name是要Distinct列的名字 dtTable = dtTable.AsEnumerable().Distinct(new ColumnEquals("column_name")).CopyToDataTable();
5中使用的new ColumnEquals("column_name") 没这个方法,去重的话可以借助groupby进行。
补充根据多列分组写法:
var erpBOMList = dt.AsEnumerable().GroupBy(G => new { t1 = G["Main_PartNo"], t2 = G["Material_PartNo"], t3 = G["Material_PartName"], t4 = G["Material_Qty"] }) .Select(s => new Mes_ERP_MaterialBOM { Main_PartNo = s.Max(m => m.Field<string>("Main_PartNo")), Material_PartNo = s.Max(m => m.Field<string>("Material_PartNo")), Material_PartName = s.Max(m => m.Field<string>("Material_PartName")), Material_Qty = s.Max(m => m.Field<decimal>("Material_Qty")), }).ToList();