Some filtering methods for DataTable: Select, dataview

Source: Internet
Author: User

When you extract some data from the database and then integrate the data, you can easily think:

DataTable dt = new DataTable (); // assume that dt is the result queried by "SELECT C1, C2, C3 FROM T1 ".
For (int I = 0; I <dt. Rows. Count; I ++)
{
If (dt. Rows [I] ["C1"]. ToString () = "abc") // query Conditions
{
// Perform the operation
}
}
However, this is a good practice once or twice. If you use more, you will get tired. Is there any better way? I remember that LinQ can directly query the able. Is there any similar method in. Net Framework 2.0? The answer is yes, that is, dt. Select (). The above operation can be changed to this:

DataRow [] drArr = dt. Select ("C1 = 'abc'"); // query
You can also perform the following operations:

DataRow [] drArr = dt. Select ("C1 LIKE 'abc % '"); // fuzzy query
DataRow [] drArr = dt. Select ("'abc' LIKE C1 + '%'", "C2 DESC"); // another fuzzy query method
DataRow [] drArr = dt. Select ("C1 = 'abc'", "C2 DESC"); // sort
The problem arises again. How can I assign a value to a new able? You may think:

DataTable dtNew = dt. Clone ();
For (int I = 0; I <drArr. Length; I ++)
{
DtNew. Rows. Add (drArr [I]);
}
But then the program will go wrong, saying that the DataRow belongs to another DataTable, what should we do? It's easy, so we can solve the problem:

For (int I = 0; I <drArr. Length; I ++)
{
DtNew. ImportRow (drArr [I]);

This completes.

 

* In addition, DataView can be used for retrieval.
*/
DataTable dataSource = new DataTable ();
DataView dv = dataSource. DefaultView;
Dv. RowFilter = "columnA = 'abc '";

DataTable newTable1 = dv. ToTable ();

DataTable newTable2 = dv. ToTable ("NewTableName ");


DataTable newTable3 =
Dv. ToTable (true, new string [] {"columnA, columnF, columnC "});

DataTable newTable4 =
Dv. ToTable ("NewTableName", true, new string [] {"columnA, columnF, columnC "});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.