Linq : select value in a datatable column

前端 未结 7 490
广开言路
广开言路 2020-12-06 09:38

How do you use LINQ (C#) to select the value in a particular column for a particular row in a datatable. The equivalent SQL would be:<

7条回答
  •  悲哀的现实
    2020-12-06 10:03

    Thanks for your answers. I didn't understand what type of object "MyTable" was (in your answers) and the following code gave me the error shown below.

    DataTable dt = ds.Tables[0];
    var name = from r in dt
               where r.ID == 0
               select r.Name;
    

    Could not find an implementation of the query pattern for source type 'System.Data.DataTable'. 'Where' not found

    So I continued my googling and found something that does work:

    var rowColl = ds.Tables[0].AsEnumerable();
    string name = (from r in rowColl
                  where r.Field("ID") == 0
                  select r.Field("NAME")).First();
    

    What do you think?

提交回复
热议问题