Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

c# - 数据表上的LINQ查询(LINQ query on a DataTable)

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.

(我试图对DataTable对象执行LINQ查询,但奇怪的是,我发现对DataTables执行此类查询并不简单。)

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?

(如何获得类似的效果?)

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

(我很惊讶在数据表上不允许使用LINQ查询!)

  ask by Calanus translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't query against the DataTable 's Rows collection, since DataRowCollection doesn't implement IEnumerable<T> .

(您无法查询DataTableRows集合,因为DataRowCollection没有实现IEnumerable<T> 。)

You need to use the AsEnumerable() extension for DataTable .

(您需要为DataTable使用AsEnumerable()扩展。)

Like so:

(像这样:)

var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;

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

(正如Keith所说,您需要添加对System.Data.DataSetExtensions的引用)

AsEnumerable() returns IEnumerable<DataRow> .

(AsEnumerable()返回IEnumerable<DataRow> 。)

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

(如果需要将IEnumerable<DataRow>转换为DataTable ,请使用CopyToDataTable()扩展名。)

Below is query with Lambda Expression,

(以下是Lambda表达式查询,)

var result = myDataTable
    .AsEnumerable()
    .Where(myRow => myRow.Field<int>("RowNo") == 1);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...