C# 使用 LINQ 查询 DataColumnCollection
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/237201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Querying DataColumnCollection with LINQ
提问by David Brown
I'm trying to perform a simple LINQ query on the Columns property of a DataTable:
我正在尝试对 DataTable 的 Columns 属性执行简单的 LINQ 查询:
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'.
找不到源类型“System.Linq.IQueryable”的查询模式的实现。未找到“选择”。考虑明确指定范围变量“c”的类型。
How can I get the DataColumnCollection to play nice with LINQ?
如何让 DataColumnCollection 与 LINQ 配合使用?
采纳答案by Dave Markle
How about:
怎么样:
var x = from c in dt.Columns.Cast<DataColumn>()
select c.ColumnName;
回答by Cobra
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.
根据Enumerable.Cast<TResult> Method
MSDN 文章,它将有效地执行与 Dave 的代码相同的操作:“在查询表达式中,显式类型的迭代变量转换为 Cast(IEnumerable) 的调用” 。
回答by MarkusE
With Linq Method Syntax:
使用 Linq 方法语法:
var x = myDataTable.Columns.Cast<DataColumn>().Select(c => c.ColumnName);