LINQ query on a DataTable

前端 未结 23 1813
执笔经年
执笔经年 2020-11-22 01:59

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:

23条回答
  •  生来不讨喜
    2020-11-22 02:07

    You can't query against the DataTable's Rows collection, since DataRowCollection doesn't implement IEnumerable. You need to use the AsEnumerable() extension for DataTable. Like so:

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

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

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

    Below is query with Lambda Expression,

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

提交回复
热议问题