码迷,mamicode.com
首页 > 其他好文 > 详细

linq to datatable 和lambda查询datatable

时间:2015-03-06 19:02:21      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

用Linq查询DataTable

        static DataTable table = new DataTable();
        static DataColumn dc = new DataColumn();
        static void Main()
        {
            Createtable();
            table.Rows.Add(1, 2,"2010-1-1");
            table.Rows.Add(2, 3, "2010-1-1");
            table.Rows.Add(3, 4, "2010-1-1");
            table.Rows.Add(4, 5, "2010-1-1");
            table.Rows.Add(5, 2, "2010-1-2");
            table.Rows.Add(6, 3, "2010-1-2");
            table.Rows.Add(7, 4, "2010-1-2");
            table.Rows.Add(8, 5, "2010-1-2");


            var query = from dt in table.AsEnumerable()
                        where new int[] { 2, 3, 4 }.Contains(dt.Field<Int32>("PID"))
                        orderby dt.Field<DateTime>("CreateDate") descending
                        group dt by dt.Field<Int32>("PID") into g
                        let n = (from d in g.Take(2).Skip(1) select d).FirstOrDefault()
                        select new
                        {
                            ID = n.Field<Int32>("ID"),
                            PID = g.Key,
                            CreateDate = n.Field<DateTime>("CreateDate")
                        };
            query.ToList().ForEach(m => Console.WriteLine("{0}\t{1}\t{2}\t",m.ID,m.PID,m.CreateDate));
        }
        public static void Createtable()
        {
            dc = new DataColumn("ID", Type.GetType("System.Int32"));
            table.Columns.Add(dc);
            dc = new DataColumn("PID", Type.GetType("System.Int32"));
            table.Columns.Add(dc);
            dc = new DataColumn("CreateDate", Type.GetType("System.DateTime"));
            table.Columns.Add(dc);
        }

 

用Lambda表达式查询DataTable

DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("UserName", System.Type.GetType("System.String"));
            DataColumn dc1 = new DataColumn("UserPwd", System.Type.GetType("System.String"));
            dt.Columns.Add(dc);
            dt.Columns.Add(dc1);
            DataRow dr = dt.NewRow();
            dr["UserName"] = "22";
            dr["UserPwd"] = "33";
            dt.Rows.Add(dr);
         
            var rownumber = dt.AsEnumerable().Where<DataRow>(C=>C["UserName"].ToString()=="22");
            int row = rownumber.Count<DataRow>();
            foreach ( DataRow en in  rownumber)
            {

                Response.Write("User" + en["UserName"] + "pwd" + en["UserPwd"]);
            }

 

linq to datatable 和lambda查询datatable

标签:

原文地址:http://www.cnblogs.com/yushuo/p/4318978.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!