【转】DataTable select根据条件取值
1、封装独立方法
// 执行DataTable中的查询返回新的DataTable /// </summary> /// <param name="dt">源数据DataTable</param> /// <param name="condition">查询条件</param> /// <returns></returns> private DataTable GetNewDataTable(DataTable dt, string condition,string sortstr) { DataTable newdt = new DataTable(); newdt = dt.Clone(); DataRow[] dr = dt.Select(condition,sortstr); for (int i = ; i < dr.Length; i++) { newdt.ImportRow((DataRow)dr[i]); } return newdt;//返回的查询结果 }
2、单独写出
DataRow[] drArr = ds.Tables[].Select("ParentID=-1", "MenuOrder asc"); DataTable dtOneLevel = ds.Tables[].Clone(); foreach (DataRow drOneLevel in drArr) { dtOneLevel.ImportRow(drOneLevel); }
3、转泛型筛选
var dtOneLevel = from dt in ds.Tables[].AsEnumerable() where dt.Field<int>("ParentId") == - orderby dt.Field<int>("MenuOrder") ascending select dt;
4、转LInq group by 求count,sum
var temp = from c in dt.AsEnumerable() group c by c.Field<int>("c3") into g select new { 卡位 = g.Key, 数量 = g.Count() }; --分组求sum var temp = from c in dt.AsEnumerable() group c by c.Field<string>("c2") into g select new { 部门= g.Key, 数量=g.Sum(c=>c.Field<int>("c3")) };