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

Lalit picture Lalit · Feb 17, 2011 · Viewed 216.8k times · Source

I know we can easily do this by a simple loop, but I want to persue this LINQ/Predicate?

string[] columnNames = dt.Columns.?

or

string[] columnNames = from DataColumn dc in dt.Columns select dc.name;

Answer

Daniel Hilgarth picture Daniel Hilgarth · Feb 17, 2011

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.