Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all column names of a DataTable into string array using (LINQ/Predicate)

People also ask

How to get all column names of DataTable in c#?

Try this (LINQ method syntax): string[] columnNames = dt. Columns. Cast<DataColumn>() .

Can you use LINQ on DataTable?

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();