Linq查询DataTable,DataRow

static void Main()
        {
            string strcon = global::TestLinqToSQL.Properties.Settings.Default.testConnectionString;
            SqlConnection conn = new SqlConnection(strcon);
            SqlDataAdapter da = new SqlDataAdapter("select * from T_Teacher", strcon);
            DataTable dt = new DataTable();
            da.Fill(dt);
            conn.Close();

            IEnumerable<DataRow> q1 = from r in dt.AsEnumerable()
                                      where r.Field<int>("ID") % 2 == 0
                                      select r;
            foreach (var item in q1)
            {
                Console.WriteLine("ID={0},Name={1},Birthday={2}", item["ID"].ToString(), item["Name"].ToString(), item["Birthday"].ToString());
            }
            Console.WriteLine("-----------------------------------");
            IEnumerable<DataRow> q2 = from r in dt.AsEnumerable()
                                      where r.Field<int>("ID")>10
                                      select r;
            foreach (var item in q2)
            {
                Console.WriteLine("ID={0},Name={1},Birthday={2}", item["ID"].ToString(), item["Name"].ToString(), item["Birthday"].ToString());
            }
            Console.WriteLine("-----------------------------------");
            DataTable dt1 = q1.CopyToDataTable();
            DataTable dt2 = q2.CopyToDataTable();
            //var except = dt2.AsEnumerable().Except(dt1.AsEnumerable() , DataRowComparer.Default); //集合排除
            //var except = dt2.AsEnumerable().Union(dt1.AsEnumerable(), DataRowComparer.Default);   //集合并
            var except = dt2.AsEnumerable().Intersect(dt1.AsEnumerable(), DataRowComparer.Default); //集合交
            foreach (var item in except)
            {
                Console.WriteLine("ID={0},Name={1},Birthday={2}", item["ID"].ToString(), item["Name"].ToString(), item["Birthday"].ToString());
            }
            Console.WriteLine("done");
            Console.ReadLine();
        }

posted @ 2010-10-13 14:06  庚武  Views(3859)  Comments(1Edit  收藏  举报