The implementation of C takes several required columns from the multi column DataTable
- 2021-09-12 01:54:20
- OfStack
This article describes the example of C # implementation from the multi-column DataTable to get the required several columns of the method. Share it for your reference, as follows:
Method 1:
It is also a well-known one:
YourDataTable.Columns.Remove(" Column name ");
However, this situation is only suitable for removing a few columns.
If there are many columns and I only need one or two columns, then I have to use method 2.
Method 2:
DataTable dat = YourDataTable.DefaultView.ToTable(false, new string[] { " The column name you want ", " The column name you want " });
Add dataTable operation related contents:
Some operations on DataTable
In dataTable, it is easy to think of using for loop to operate, but in fact, form loop will not be used unless absolutely necessary, because the efficiency is not high.
1) Row fetch
Take line 1 and use rowfilter
DataTable datSource;// Data source table
// Filter table
DataView davTemp = new DataView(datSource, " Filter condition ", " Sort field ", DataViewRowState. Various Status );
// Assign the filtered table to the new table
DataTable datNew = davTemp.ToTable();
2) Fetch 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 [provided the table structure or the number of columns is the same]
DataTable datSource;
DataTable datNew;
datSource.Rows[i].ItemArray= datNew. Rows[i].ItemArray;
4) The number of columns in the table is the same, but the column names are different. What should I do if I want to copy the value?
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 3 Column
dat.Columns.Add("col1");
dat.Columns.Add("col2");
dat.Columns.Add("col3");
// Add 1 Row data
dat.Rows.Add(1,2,3);
// Put the first 3 Column placed in 1 Location of
dat.Columns["col3"].SetOrdinal(0);
I hope this article is helpful to everyone's C # programming.