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 = 0; i < dr.Length; i++)
            {
                newdt.ImportRow((DataRow)dr[i]);
            }
            return newdt;//返回的查询结果
        }
View Code

2、单独写出

DataRow[] drArr = ds.Tables[0].Select("ParentID=-1", "MenuOrder asc");
                DataTable dtOneLevel = ds.Tables[0].Clone();
                foreach (DataRow drOneLevel in drArr) 
                {
                    dtOneLevel.ImportRow(drOneLevel);
                }
View Code

3、转泛型筛选

   var dtOneLevel = from dt in ds.Tables[0].AsEnumerable()
                                 where dt.Field<int>("ParentId") == -1
                                 orderby dt.Field<int>("MenuOrder") ascending
                                 select dt;
View Code

 

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

posted @ 2015-11-24 18:54  Mark1997  阅读(920)  评论(0编辑  收藏  举报