Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Select From DataTable

Tags:

c#

linq

ado.net

Just started to play around with datatable and LINQ today. I have a datatable that gets a list of Names From SQL database. I am looking to return a specific name from the dt using LINQ.

I have tried the following code with no success at this. Is there something that i am doing wrong with the code.

dt returns a full list of names i am just looking to reduce the names down to one name. There is a name in the adventureworks database called Blade i am trying to display this only.

 DataTable dt =  DAL.GetNames();
      try
      {
          var q = from myrow in dt.AsEnumerable()
                  where myrow.Field<string>("Name") =="Blade"
                  select myrow;
          dataGridView1.DataSource = q;
      }

I have tried to replace the == with a .equals. I am totally new to the concept of using a Language intergrated query.

when i run the code noting happens i dont get any errors ect just no data returned.

like image 249
Inkey Avatar asked Feb 21 '13 20:02

Inkey


People also ask

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.

How can you load data into a DataSet so that it can be queried using LINQ?

Data sources that implement the IEnumerable<T> generic interface can be queried through LINQ. Calling AsEnumerable on a DataTable returns an object which implements the generic IEnumerable<T> interface, which serves as the data source for LINQ to DataSet queries.

How do I select a particular column value in LINQ?

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


1 Answers

You're defining your query but not actually running it.

Your line:

dataGridView1.DataSource = q;

Needs to be:

dataGridView1.DataSource = q.AsDataView();
like image 173
Jesse Avatar answered Sep 30 '22 16:09

Jesse