Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq : select value in a datatable column

Tags:

c#

linq

datatable

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:

select NAME from TABLE where ID = 0 

Thanks in advance.

like image 832
ianbeks Avatar asked Dec 10 '09 10:12

ianbeks


People also ask

How to get specific column value from DataTable in c#?

How to get the column value from the data table. Can try as: string countryName = "USA"; DataTable dt = new DataTable(); int id = (from DataRow dr in dt. Rows where (string)dr["CountryName"] == countryName select (int)dr["id"]).

How to get column value using linq in c#?

var Q1 = (ds. Tables[1]. AsEnumerable() .

Can we use LINQ to query against a DataTable?

Can we use linq to query against a DataTable? Explanation: We cannot use query against the DataTable's Rows collection, since DataRowCollection doesn't implement IEnumerable<T>. We need to use the AsEnumerable() extension for DataTable.


2 Answers

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<int>("ID") == 0               select r.Field<string>("NAME")).First<string>(); 

What do you think?

like image 79
ianbeks Avatar answered Sep 20 '22 15:09

ianbeks


var name = from r in MyTable             where r.ID == 0             select r.Name; 

If the row is unique then you could even just do:

var row = DataContext.MyTable.SingleOrDefault(r => r.ID == 0); var name = row != null ? row.Name : String.Empty; 
like image 35
James Avatar answered Sep 20 '22 15:09

James