linq to datatable 和lambda查询datatable

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

 

posted @ 2015-03-06 18:17  EasyCms-  阅读(5225)  评论(0编辑  收藏  举报