Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying DataColumnCollection with LINQ

I'm trying to perform a simple LINQ query on the Columns property of a DataTable:

from c in myDataTable.Columns.AsQueryable()
    select c.ColumnName

However, what I get is this:

Could not find an implementation of the query pattern for source type 'System.Linq.IQueryable'. 'Select' not found. Consider explicitly specifying the type of the range variable 'c'.

How can I get the DataColumnCollection to play nice with LINQ?

like image 404
David Brown Avatar asked Oct 25 '08 23:10

David Brown


3 Answers

How about:

var x = from c in dt.Columns.Cast<DataColumn>()
        select c.ColumnName;
like image 182
Dave Markle Avatar answered Nov 07 '22 19:11

Dave Markle


You could also use:

var x = from DataColumn c in myDataTable.Columns
        select c.ColumnName

It will effectively do the same as Dave's code: "in a query expression, an explicitly typed iteration variable translates to an invocation of Cast(IEnumerable)", according to the Enumerable.Cast<TResult> Method MSDN article.

like image 34
Cobra Avatar answered Nov 07 '22 19:11

Cobra


With Linq Method Syntax:

var x = myDataTable.Columns.Cast<DataColumn>().Select(c => c.ColumnName);
like image 12
MarkusE Avatar answered Nov 07 '22 20:11

MarkusE