Home > Software engineering >  Accessing the List-Property of a DataColumnCollection of a DataTable
Accessing the List-Property of a DataColumnCollection of a DataTable

Time:12-22

I am trying to access the List-Property of the DataColumnCollection of a DataTable, and it seems like there is none. The access is necessary, for there is a collection of strings ("Format") that I need to process after the extraction from the DataTable.

The documentation of Microsoft says, that it is accessible via the Columns of the DataTable (https://docs.microsoft.com/en-us/dotnet/api/system.data.datatable?view=net-6.0), but it isn't.

foreach (object item in dataTable.Columns.List)  // .List is marked as error
{
    Console.WriteLine("TEST: "   item.Format);   // .Format (is string) is marked as error
}

I know that the List-Property is at least getable and that's all I need. I believe that I'm missing something very obvious here... any Ideas?

CodePudding user response:

DataColumnCollection is derived from InternalDataCollectionBase which itself is a collection, so your dataTable.Columns themselves is a list, you don't need to do columns.List

This is how you can access the properties of each column.

DataColumnCollection columns = table.Columns;

// Get the ColumnName and DataType for every column.
foreach(DataColumn dataColumn in columns)
{
    Console.WriteLine(dataColumn.ColumnName);
    Console.WriteLine(dataColumn.DataType);
}

CodePudding user response:

Try to use linq

var dtColumn = from item in dataTable.Columns.Cast<DataColumn>()
select item.ColumnName;
  • Related