Get all column names of a DataTable into string array using (LINQ/Predicate)
Try this (LINQ method syntax):
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
or in LINQ Query syntax:
string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>()
select dc.ColumnName).ToArray();
Cast
is required, because Columns is of type DataColumnCollection which is a IEnumerable
, not IEnumerable<DataColumn>
. The other parts should be obvious.
Use
var arrayNames = (from DataColumn x
in dt.Columns.Cast<DataColumn>()
select x.ColumnName).ToArray();
I'd suggest using such extension method:
public static class DataColumnCollectionExtensions
{
public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
{
return source.Cast<DataColumn>();
}
}
And therefore:
string[] columnNames = dataTable.Columns.AsEnumerable().Select(column => column.Name).ToArray();
You may also implement one more extension method for DataTable
class to reduce code:
public static class DataTableExtensions
{
public static IEnumerable<DataColumn> GetColumns(this DataTable source)
{
return source.Columns.AsEnumerable();
}
}
And use it as follows:
string[] columnNames = dataTable.GetColumns().Select(column => column.Name).ToArray();