LINQ query on a DataTable(对 DataTable 的 LINQ 查询)
问题描述
我正在尝试对 DataTable 对象执行 LINQ 查询,但奇怪的是,我发现对 DataTables 执行此类查询并不简单.例如:
I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:
var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;
这是不允许的.我怎样才能让这样的事情发挥作用?
This is not allowed. How do I get something like this working?
我很惊讶在 DataTables 上不允许使用 LINQ 查询!
I'm amazed that LINQ queries are not allowed on DataTables!
推荐答案
你不能查询 DataTable 的 Rows 集合,因为 DataRowCollection 没有实现 IEnumerable<T>.您需要为 DataTable 使用 AsEnumerable() 扩展.像这样:
You can't query against the DataTable's Rows collection, since DataRowCollection doesn't implement IEnumerable<T>. You need to use the AsEnumerable() extension for DataTable. Like so:
var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;
正如 @Keith 所说,您需要添加对 System.Data.DataSetExtensions
And as @Keith says, you'll need to add a reference to System.Data.DataSetExtensions
AsEnumerable() 返回 IEnumerable.如果您需要将 IEnumerable<DataRow> 转换为 DataTable,请使用 CopyToDataTable() 扩展.
AsEnumerable() returns IEnumerable<DataRow>. If you need to convert IEnumerable<DataRow> to a DataTable, use the CopyToDataTable() extension.
下面是使用 Lambda 表达式的查询,
Below is query with Lambda Expression,
var result = myDataTable
.AsEnumerable()
.Where(myRow => myRow.Field<int>("RowNo") == 1);
这篇关于对 DataTable 的 LINQ 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对 DataTable 的 LINQ 查询
基础教程推荐
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
