• [转]Linq查询DataTable,DataRow


     原文:http://www.cnblogs.com/wucg/archive/2010/10/13/1850053.html

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


  • 相关阅读:
    Merge k Sorted Lists
    N-Queens
    N-Queens II
    Reorder List
    使用AJAX实现文件上传时Illegal invocation错误
    php页面开启错误提示
    php分割最后一个逗号后面的字符
    微信卡券添加(微擎系统)
    php请求php
    Navicat MySQL连接Linux下MySQL的问题解决方案
  • 原文地址:https://www.cnblogs.com/greatwang/p/3292539.html
Copyright © 2020-2023  润新知