Home > database >  Remove all columns from datatable except for 25
Remove all columns from datatable except for 25

Time:10-20

I have 500 Columns in my DataTable and I want to remove all of them except for 25 columns.

Is there any way to do this faster to save time and lines of code?

This is what I already tried:

private static void DeleteUselessColumns()
{
    //This is example data!
    List<DataColumn> dataColumnsToDelete = new List<DataColumn>();
    DataTable bigData = new DataTable();
    bigData.Columns.Add("Harry");
    bigData.Columns.Add("Konstantin");
    bigData.Columns.Add("George");
    bigData.Columns.Add("Gabriel");
    bigData.Columns.Add("Oscar");
    bigData.Columns.Add("Muhammad");
    bigData.Columns.Add("Emily");
    bigData.Columns.Add("Olivia");
    bigData.Columns.Add("Isla");
    
    List<string> columnsToKeep = new List<string>();
    columnsToKeep.Add("Isla");
    columnsToKeep.Add("Oscar");
    columnsToKeep.Add("Konstantin");
    columnsToKeep.Add("Gabriel");
    
    foreach (DataColumn column in bigData.Columns)
    {
        bool keepColumn = false;
        foreach (string s in columnsToKeep)
        {
            if (column.ColumnName.Equals(s))
            {
                keepColumn = true;
            }
        }
        if (!keepColumn)
        {
            dataColumnsToDelete.Add(column);
        }
    }
    
    foreach(DataColumn dataColumn in dataColumnsToDelete)
    {
        bigData.Columns.Remove(dataColumn);
    }
}    

CodePudding user response:

var wanted = new List<string>() { "Test2", "Test4", "Test6" };
var toremove = new List<DataColumn>();

foreach(DataColumn column in bigData.Columns)
{
  if (!wanted.Any(w => column.ColumnName == w))
  {
     toremove.Add(column);
  }
}

toremove.ForEach(col => bigData.Columns.Remove(col));

CodePudding user response:

Test1...test9 same code could be made a loop. No need to add the columns to delete in a list, just delete them in the first while loop. As for performance, not sure how to improve it.

You could try to use a DataView that selects the desired columns then copy to table. You need to experiment.

CodePudding user response:

if they have different names create an array of string

var columns = new string[] { "Harry", "Konstantin","John"};
 var columnsToKeep = new string[] { "John", "Konstantin"};

    var columnsToDelete = from item in columns
                where !columnsToKeep.Contains(item)
                select item;

or using lambda

   var columnsToDelete = columns
                    .Where (i=> !columnsToKeep.Contains(i))
                    .ToList();

toDelete

Harry
  • Related