Reputation: 872
I have a GridView(gv). And a DataTable(dt). I'd like to be able to use Linq to get lists of just their column names.
I know that gv.Columns is a collection of GridViewDataColumns and has a "Name" property. I also know that dt.Columns is a collection of DataColumns and has a "ColumnName" property.
I was trying to do something like:
Dim gvList as List(Of String) = gv.Columns.Select(x=>x.Name).ToList()
Dim dtList as List(Of String) = dt.Columns.Select(y=>y.ColumnName).ToList()
but I am getting errors an error that says I need parenthesis. Am I even heading in the right direction?
Thanks!
Upvotes: 1
Views: 2362
Reputation: 205769
Both DataGridViewColumnCollection and DataColumnCollection classes in question are from "pre generic" times of .NET, so they don't implement IEnumerable<T>
, thus are not directly usable for LINQ query operators.
Fortunately they implement IEnumerable
, so you can use Enumerable.Cast first to turn them into a IEnumerable<T>
, like this (C# code):
var gvList = gv.Columns.Cast<DataGridViewColumn>().Select(c => c.Name).ToList();
var dtList = dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName).ToList();
Upvotes: 2