Try this (LINQ method syntax): string[] columnNames = dt. Columns. Cast<DataColumn>() .
Linq can help to perform complex queries on a datatable easily. We can use the different querying capabilities of the linq for performing different operations. For example we can project only few specific columns from a datatable using the select operation.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With