84

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?

David Brown
  • 35,411
  • 11
  • 83
  • 132

3 Answers3

143

How about:

var x = from c in dt.Columns.Cast<DataColumn>()
        select c.ColumnName;
Dave Markle
  • 95,573
  • 20
  • 147
  • 170
  • 3
    @Dave: What causes this issue in the first place? How come we have to do the Cast() ? – Ryan Shripat Mar 13 '09 at 17:20
  • 27
    It's because dt.Columns is an IEnumerable, but not an IEnumerable. It's just a function of the fact that the class is a bit older and doesn't implement the new generic type. When you Cast<>(), you cast to an IEnumerable where the extension methods are defined. – Dave Markle Mar 31 '09 at 00:16
16

With Linq Method Syntax:

var x = myDataTable.Columns.Cast<DataColumn>().Select(c => c.ColumnName);
MarkusE
  • 545
  • 4
  • 20
16

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.

Cobra
  • 352
  • 3
  • 12