Bestimmte Spalten eines DataTables in einen neuen DataTable schreiben



  • Hallo zusammen,

    gibt es eine elegante Lösung in C# um bestimmte Spalten eines DataTables in einen neuen DataTable zu schreiben?

    private DataTable test(List<string> col, DataTable table)
            {
                var newtable = new DataTable();
    
                foreach (var item in col)
                {
                    newtable.Columns.Add(item);
                    /* Schreibe Spalte item aus table in Spalte item aus newtable ??? */
                }
    
                return newtable;
            }
    

    Danke schon einmal.

    Grüße
    doemi



  • So habe es hinbekommen, aber vielleicht gibt es noch eine elegantere Lösung?

    private DataTable test(List<string> col, DataTable table)
            {
                var newtable = new DataTable();
                var columns = table.Columns;
    
                foreach (var item in col)
                {
                    for (int i = table.Columns.Count - 1; i >= 0 ; i-- )
                    {
                        if (!(col.Contains(table.Columns[i].ColumnName)))
                        {
                            var column = new DataColumn();
                            column = (DataColumn)table.Columns[i];
                            table.Columns.RemoveAt(columns.IndexOf(column));
                        }
                    }
                }
    
                newtable = table;
    
                return newtable;
    

Anmelden zum Antworten