SoFunction
Updated on 2025-03-08

DataTable sorting, retrieval, merge operation examples in C#

1. Sort
1. Get the default view of DataTable
2. Set a sort expression for the view
3. Replace the DataTable with the new DataTable exported by the sorted view (Asc can be omitted ascending order, and multiple column sorting is separated by ",")
1) Rebirth method

Copy the codeThe code is as follows:
(dt)
(0). = "id desc"

2) Direct method
Copy the codeThe code is as follows:
dv = New DataView(dt)
= "id desc"
dt = ();

3) Indirect method
Copy the codeThe code is as follows:
dv = New DataView([0])
= "id desc"
dt = ();


2. Search

Set query string
Use the Select method to obtain an array of data row objects that meet the conditions (multiple query conditions are separated by and)
Copy the codeThe code is as follows:
DataRow[] matches = ("id<'003' and name='name11'");
string strName = matches[0]["name"].ToString();

3. Merger

Suppose there are 2 DataTables: Dt1 , Dt2 . The same table structure
This method can be used after connecting Dt2 to Dt1

Copy the codeThe code is as follows:
(dt2);


4. Issues that should be paid attention to when querying in DataTable

After completing a query and returning a DataTable, I often want to continue searching in the query results. At this time, you can use the method to query the results again
The Select method has 4 overloads, and what we often use is (String)
The parameters of this String are the qualifiers of the query. It is equivalent to the WHERE statement (excluding WHERE) in the SQL query language, and its syntax conforms to the SQL language syntax.
The Select method returns a DataRow containing the queryed data, but this DataRow is just a map of the queryed DataTable, so the DataRow changes with the row changes of the DataTable. For example, if all the rows of DataTable are deleted, then the data in DataRow is also deleted (even if it is selected first, then deleted)
Therefore, if you want to put the returned DataRow into the data display control, you need to put it into another DataTable. If you put it directly into the original DataTable or clear all the rows of the original DataTable and then put it into the query data, the program will display an error, and the error prompt is "This row already exists in the table".
In addition, inserting rows in a new table cannot be used directly (DataRow) because this is to insert a new table, that is, DataRow is empty. To import rows, (DataRow). Of course, the premise is that this new table must have the same structure as the original data table.

Copy the codeThe code is as follows:
Public Function SDEResearch(ByVal InputDT As DataTable, ByVal SearchStr As String) As DataTable

'Use to store the re-queried data table
Dim ResearchDT As DataTable = () 'Ensure that there is the same table structure as the source data table

'Use to store the datarow array returned after query
Dim ReSearchDR() As DataRow = Nothing

Try
ResearchDR = ("NAME LIKE '%" + SearchStr + "%'") 'Just map datarow() from the data table, so the rows in the original table cannot be deleted
Catch ex As Exception
Return Nothing
End Try

For i As Int16 = 0 To - 1
(ReSearchDR(i))
Next

Return ReSearchDT
End Function

Attached:How to filter DataTable data

Some methods for filtering and filtering DataTable Select, dataview
When you take some data out of the database and then integrate the data, it is easy to think of:

Copy the codeThe code is as follows:
DataTable dt = new DataTable();//Suppose dt is the result of querying "SELECT C1, C2, C3 FROM T1"
for (int i = 0; i < ; i++)
{
if ([i]["C1"].ToString() == "abc")//Query conditions
    {
//Perform operation
    }
}

But it’s okay to use this method once or twice, but you will get tired if you use it too much. So is there a better way? Remember LinQ can directly query DataTable. Is there a similar method in .Net Framework 2.0? The answer is yes, that is (), the above operation can be changed to this:
Copy the codeThe code is as follows:
DataRow[] drArr = ("C1='abc'");//Query

You can also do this:
Copy the codeThe code is as follows:
DataRow[] drArr = ("C1 LIKE 'abc%'");//Fuzzy query
DataRow[] drArr = ("'abc' LIKE C1 + '%'", "C2 DESC");//Another method of fuzzy query
DataRow[] drArr = ("C1='abc'", "C2 DESC");//Sort

The question is again. If you want to assign DataRow to a new DataTable, how to assign it? You may think of:
Copy the codeThe code is as follows:
DataTable dtNew = ();
for (int i = 0; i < ; i++)
{
    (drArr[i]);
}

But in this way the program will make an error, saying that the DataRow belongs to other DataTables, so how to do it? It's very simple, so it can be solved:
Copy the codeThe code is as follows:
DataTable dtNew = ();
for (int i = 0; i < ; i++)
{
    (drArr[i]);
}

This is done.
DataRow[] in 3.5 has an extension method CopyToDataTable()
Copy the codeThe code is as follows:
/*
* To add, you can also use DataView to achieve the purpose of retrieval.
*/
DataTable dataSource = new DataTable();
DataView dv = ;
= "columnA = 'abc'";
//1. After filtering, directly obtain DataTable
DataTable newTable1 = ();
//2. Set the TableName of the new DataTable
DataTable newTable2 = ("NewTableName");
//3. Set whether the new table filters duplicates, the column names of the owned columns and the order in which they appear
//The fields of the new table can be set. But the field name must be owned by the old cousin dataSource.
DataTable newTable3 =
(true, new string[] { "columnA,columnF,columnC" });
//4. Comprehensive 2.3 points.
DataTable newTable4 =
("NewTableName", true, new string[] { "columnA,columnF,columnC" });