对DataTable数据进行查询过滤

          //对DataTable数据进行查询过滤并返回DataTable

        //1、DataTable.Select(where);
        //2、DataView.RowFilter
        //3、Linq

        #region 创建一个表dt,并给其添加6行数据
        DataTable dt = new DataTable();
        dt.Columns.Add("ID", typeof(System.Int32));
        dt.Columns.Add("Name", typeof(System.String));
        dt.Columns.Add("Address", typeof(System.String));
        DataRow row1 = dt.NewRow();
        row1[0] = 1;
        row1[1] = "AdminAdmin";
        row1[2] = "Test";
        dt.Rows.Add(row1);
        DataRow row2 = dt.NewRow();
        row2[0] = 2;
        row2[1] = "AdmioknA";
        row2[2] = "Test";
        dt.Rows.Add(row2);
        DataRow row3 = dt.NewRow();
        row3[0] = 3;
        row3[1] = "AdminjunjieAdmin";
        row3[2] = "Test";
        dt.Rows.Add(row3);
        DataRow row4 = dt.NewRow();
        row4[0] = 4;
        row4[1] = "Admokin";
        row4[2] = "Test";
        dt.Rows.Add(row4);
        DataRow row5 = dt.NewRow();
        row5[0] = 5;
        row5[1] = "AdminAokdmijunjien";
        row5[2] = "Test";
        dt.Rows.Add(row5);
        DataRow row6 = dt.NewRow();
        row6[0] = 6;
        row6[1] = "Admin";
        row6[2] = "Test";
        dt.Rows.Add(row6);
#endregion

        //1、使用DataTable.Select(where);
        var newtable1 = dt.Clone();//把源表的结构给新表
        foreach (DataRow row in dt.Select("Name like '%ok%'"))
        {
            newtable1.ImportRow(row);
        }

        //2、使用DataView.RowFilter
        DataView dv = dt.DefaultView; ;
        dv.RowFilter = "Name like '%ok%'";
        var newdatatable2 = dv.ToTable();

        //3、使用linq
        var newtable3 = (from datarow in dt.AsEnumerable() where datarow.Field<string>("Name").IndexOf("ok") > -1 select datarow).CopyToDataTable();

        //如果数据量小,DataTable.Select()与DataView.RowFilter没有什么大的区别。如果数据量大,用DataView.RowFilter则比较快。linq不太了解

posted on 2012-03-20 17:19  VincentZhu  阅读(1562)  评论(0编辑  收藏  举报