When you take some data out of a database and then integrate it, it's easy to think:
1DataTable dt =NewDataTable ();//Suppose DT is the result of a "select c1,c2,c3 from T1" Query2 for(inti =0; i < dt. Rows.Count; i++) 3 { 4 if(dt. rows[i]["C1"]. ToString () = ="ABC")//Query Criteria5 { 6 //to operate7 } 8}
View Code
But this practice with one or two times fortunately, with more tired. Is there a better way to do that? Remember that LINQ can query the DataTable directly, is there a similar approach in the. Net Framework 2.0? The answer is yes, that is dt. Select (), the above operation can be changed to this:
1datarow[] Drarr = dt. Select ("c1= ' abc '");//Enquiry2 //You can also do this:3 4datarow[] Drarr = dt. Select ("C1 like ' abc% '");//Fuzzy Query5datarow[] Drarr = dt. Select ("' abc ' like C1 + '% '","C2 DESC");//Another method of fuzzy query6datarow[] Drarr = dt. Select ("c1= ' abc '","C2 DESC");//Sort
View Code
Again, if you want to assign a DataRow to a new DataTable, how do you assign a value? You might think:
1 DataTable dtnew =2 for (int0; i < drarr.length; i++ 345 }
View Code
But this procedure will be wrong, said the DataRow belongs to other DataTable, how to do it? Very simple, so it can be solved:
1 DataTable dtnew =2 for (int0; i < drarr.length; i++ 3 4 dtnew.importrow (Drarr[i]); 5 6 }
View Code
Add, you can also use DataView to achieve the purpose of the search.
1DataTable DataSource =NewDataTable ();2DataView DV =Datasource.defaultview;3Dv. RowFilter ="ColumnA = ' abc '";4 5 //1. Direct access to the DataTable after filtering6DataTable NewTable1 =DV. ToTable ();7 8 //2. Setting the TableName of the new DataTable9DataTable newTable2 = dv. ToTable ("Newtablename");Ten One //3. Set whether the new table filters duplicates, the column names of the columns that are owned, and the order in which they appear A //that is, you can set the fields for the new table. But the field names are definitely owned by cousin DataSource. -DataTable NewTable3 = -Dv. ToTable (true,New string[] {"COLUMNA,COLUMNF,COLUMNC" }); the - //4.2.3 Two points were synthesized. -DataTable newTable4 = -Dv. ToTable ("Newtablename",true,New string[] {"COLUMNA,COLUMNF,COLUMNC"});
View Code
Ways to filter data in a DataTable