How to get the value of a DataTable by applying LINQ

0

How to obtain the value of a field from a DataTable? I have managed to get the value of a field from a DataTable in the following way.

var strSQL = "SELECT Id, Descripcion FROM Mensajes";
var dt = GetAll(strSQL);
string result = dt.Rows[0][1].ToString();

But applying LINQ I have tried it in the following way but I do not get it.

string result = dt.Rows.Cast<DataRow>().Select(x => x.Field<string>("Descripcion")).ToString();
    
asked by Pedro Ávila 31.10.2016 в 02:37
source

1 answer

2

You want to get the value of the first row, if you use only the Select () you return a list, then you must apply the First ()

string result = dt.Rows.Cast<DataRow>().Select(x => x.Field<string>("Descripcion")).First();

If you want to continue with your technique you could do

var descriptions = dt.Rows.Cast<DataRow>().Select(x => x.Field<string>("Descripcion")).ToList();

string result = descriptions[0];

in this case you get the list of descriptions and of this the first item

    
answered by 31.10.2016 / 04:24
source