Querying DataColumnCollection with LINQ

C#LinqDatatableAsqueryableDatacolumncollection

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

How about:

var x = from c in dt.Columns.Cast<DataColumn>()
        select c.ColumnName;

Solution 2 - C#

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.

Solution 3 - C#

With Linq Method Syntax:

var x = myDataTable.Columns.Cast<DataColumn>().Select(c => c.ColumnName);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid BrownView Question on Stackoverflow
Solution 1 - C#Dave MarkleView Answer on Stackoverflow
Solution 2 - C#CobraView Answer on Stackoverflow
Solution 3 - C#MarkusEView Answer on Stackoverflow