简体   繁体   中英

How to get one datatable with two columns from another datatable with many columns in C#

I have one data Table with 15 columns and many rows and I need to create a new data Table that only has three columns of the 15 columns and copy all the corresponding data from the original data table to the second data table.

I have looked for an answer and the closest I have found is the following URL .But my problem with using the SO solution is that I need to remove 12 columns in order to get my 3 desired columns, as the SO solution is removing columns.

Is there an easier way to do this? Any hint would be appreciated. I don't know LINQ (Maybe this is a LINQ question, I don't know) and I am an intermediate C# programmer. Thanks for your help.

SO Solution That is close to what I need

Edited Later: This Solved My Problem With many thanks to @Tim Schmelter for his response, after I posted this question I saw that at the end of the day what I need to do is to copy the final data table (with three columns) to a dataGridView (that already has three columns). So my question would then be how to copy a dataTable with 15 columns to a DataGridView with 3 columns. And I found my answer by looking at Nomi Ali's comment in the second SO link in my post . I simply set the AutoGenerateColumn to False on the DataGridView. That solved my problem. However I will try @Tim Schmelter's answer and if that works I will mark it as an answer.

Perhaps you could define a white-list and use LINQ:

string[] wantedColumns = { "Column1", "Column2", "Column3" }; // for example
DataTable secondTable = firstTable.Copy();
var removeColumns = secondTable.Columns.Cast<DataColumn>()
    .Where(col => !wantedColumns.Contains(col.ColumnName, StringComparer.InvariantCultureIgnoreCase))
    .ToList();
removeColumns.ForEach(c => secondTable.Columns.Remove(c));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM