在一个DataTable的LINQ查询DataTable、LINQ

由网友(漂亮嫂子)分享简介:我想在一个DataTable对象执行LINQ查询,奇怪的是,我发现,在数据表执行此类查询并不简单。例如:I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such qu...

我想在一个DataTable对象执行LINQ查询,奇怪的是,我发现,在数据表执行此类查询并不简单。例如:

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?

我很惊讶,LINQ查询没有数据表允许的!

I'm amazed that LINQ queries are not allowed on DataTables!

推荐答案

您不能对数据表的行的集合查询,因为 DataRowCollection 不执行的IEnumerable< T> 。你需要使用 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;

和基思说,你需要添加一个引用到System.Data.DataSetExtensions

And as Keith says, you'll need to add a reference to System.Data.DataSetExtensions

AsEnumerable()返回的IEnumerable&LT; D​​ataRow的&GT; 。如果你需要转换的IEnumerable&LT; D​​ataRow的&GT; 数据表,使用 CopyToDataTable() 扩展。

AsEnumerable() returns IEnumerable<DataRow>. If you need to convert IEnumerable<DataRow> to a DataTable, use the CopyToDataTable() extension.

阅读全文

相关推荐

最新文章