C # Some DataTable operations are frequently performed,
Operations on C # DataTable
Frequent operations on DATATABLE can achieve the same effect for some operations that do not need to be repeated through SQL.
Method 1:
It is also widely known:
YourDataTable. Columns. Remove ("column name ");
However, this situation is only suitable for removing a small number of columns.
If there are many columns, but I only need one or two columns, method 2 is required.
Method 2:
DataTable dat = YourDataTable. DefaultView. ToTable (false, new string [] {"Name of the column you want", "Name of the column you want "});
Add a able:
Operations on DataTable
The easiest thing to think of in a dataTable is to use a for loop for operations, but it is not a last resort because the efficiency is generally not high.
1) Fetch rows
Rowfilter is generally used for row fetch.
DataTable datSource; // data source table
// Filter the table
DataView davTemp = new DataView (datSource, "filter condition", "Sort field", DataViewRowState. Various statuses );
// Assign the filtered table to the new table
DataTable datNew = davTemp. ToTable ();
2) retrieve one or more columns of the table
DataTable datSource; // data source table
DataTable datNew = datSource. DefaultView. ToTable (false, new string [] {"column name", "column name ".....});
3) copy the value of a row [if the table structure or number of columns are the same]
DataTable datSource;
DataTable datNew;
DatSource. Rows [I]. ItemArray = datNew. Rows [I]. ItemArray;
4) What if I want to copy a table with the same number of columns but different column names?
In another way of thinking, since the number of columns is the same, but the column names are different, why not change the column names?
As follows:
DataTable datSource;
DataTable datNew;
DatNew = datSource. Copy ();
DatNew. Columns ["FirstColumn"]. ColumnName = "YourColumnName ";
5) Adjust the column position SetOrdinal ();
DataTable dat = new DataTable ();
// Add three columns
Dat. Columns. Add ("col1 ");
Dat. Columns. Add ("col2 ");
Dat. Columns. Add ("col3 ");
// Add a row of data
Dat. Rows. Add (1, 2, 3 );
// Place the third column to the first position
Dat. Columns ["col3"]. SetOrdinal (0 );