Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Select DataRow from DataTable

Tags:

c#

linq

I have a DataTable i am trying to do a simple select row that contains a value.

My code

  var LoginDetails = from myRow in DTOperators.AsEnumerable()
                           where myRow.Field<string>(0) == UserName
                           select myRow;

I am trying to check if the string UserName exists at position 0 the rows in the datatable

When i run this query i get a blank datarow back.

I have tried to use [] around the position that i want to select.

anyone able to see what i am doing wrong.

like image 903
Inkey Avatar asked Aug 16 '13 11:08

Inkey


1 Answers

you have to check if you comparing with right column and check data in your table. this work fine:

var DTOperators = new DataTable();
var UserName = "test";
DTOperators.Columns.Add("UserName", typeof(string));
DTOperators.Rows.Add("test1");
DTOperators.Rows.Add("test");
var LoginDetails = from myRow in DTOperators.AsEnumerable()
                     where myRow.Field<string>(0) == UserName
                     select myRow;

I've got Enumerable with one datarow. You also could try to get data by columnName:

var LoginDetails = DTOperators.Rows
                              .Cast<DataRow>()
                              .Where(x => x["UserName"] == UserName).ToList();
like image 177
Roman Pekar Avatar answered Oct 22 '22 17:10

Roman Pekar