LINQ query on a DataTable

前端 未结 23 1436
执笔经年
执笔经年 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:29

    I realize this has been answered a few times over, but just to offer another approach:

    I like to use the .Cast() method, it helps me maintain sanity in seeing the explicit type defined and deep down I think .AsEnumerable() calls it anyways:

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

    or

    var results = myDataTable.Rows.Cast()
                          .FirstOrDefault(x => x.Field("RowNo") == 1);
    

    As noted in comments, no other assemblies needed as it's part of Linq (Reference)

提交回复
热议问题