DataTable row sorting method
This article introduces a method to sort DataTable rows based on specific columns. Suppose we have a DataTable containing the following data, containing two columns:
COL1 | COL2 |
---|---|
Abc | 5 |
Def | 8 |
Ghi | 3 |
Our goal is to sort the data in descending order based on the value of the COL2 column and get the following results:
COL1 | COL2 |
---|---|
Def | 8 |
Abc | 5 |
Ghi | 3 |
Initially tried using the following code:
<code>ft.DefaultView.Sort = "COL2 desc"; ft = ft.DefaultView.ToTable(true);</code>
However, this method sorts the DataView, not the DataTable directly.
Solution
It is not easy to sort DataTable directly in place. The recommended method is: first create a DataView from the original DataTable, then sort or filter the DataView, and finally use the DataView.ToTable method to create a new DataTable.
<code>DataView dv = ft.DefaultView; dv.Sort = "COL2 desc"; DataTable sortedDT = dv.ToTable();</code>
This method can sort the DataTable efficiently and does not modify the original DataTable.
The above is the detailed content of How to Efficiently Sort DataTable Rows by a Specific Column in Descending Order?. For more information, please follow other related articles on the PHP Chinese website!