4

Can anyone tell me why this doesn't compile? The error is:

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace caLINQ
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "Data Source=STEVEN-PC\\SQLEXPRESS;Initial Catalog=linqtest;Integrated Security=True;Pooling=False";
            using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
            {
                 connection.Open();
                 String cmdText = "select * from customers";
                 System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(cmdText, connection);
                 System.Data.SqlClient.SqlDataReader dr;
                 dr = cmd.ExecuteReader();
                 DataSet ds = new DataSet();
                 ds.Load(dr, LoadOption.OverwriteChanges, "tab1");
                 DataTable dt = ds.Tables[0];
                 var qy = from c in dt // error is here
                          where c.country == "Italy"
                          select c.name;
            }
            Console.ReadKey();
        }
    }
}
2
  • You should be looking at using Linq2Sql instead of filling datatables and querying those. Commented Jun 25, 2012 at 16:32
  • 2
    Hi, welcome. You may consider marking one of the answers as accepted by ticking the big check mark at the left of it. Commented Jun 25, 2012 at 20:49

2 Answers 2

12

Try:

var qy = from c in dt.AsEnumerable()
         where c.Field<string>("country") == "Italy"
         select c.Field<string>("name");

AsEnumerable() will return an IEnumerable<DataRow> that can be used with LINQ.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Magnus and KreepN. After implementing both your suggestions it worked. It is a trivial app that I am just using to try to get to know LINQ; I figured I would start by filling a DataTable and trying to query it. Now I can move on. SLB
AsEnumerable() is costly
@StackOrder not on a DataTable
4

Adjust your code to (I'm assuming that your DB columns are "country" and "name):

var qy = from DataRow c in dt.Rows
         where c.Field<string>("country") == "Italy"
         select c.Field<string>("name");

Or

var qy = (from DataRow c in dt.Rows
         where c.Field<string>("country") == "Italy"
         select c.Field<string>("name")).ToList()

For a list of those "names".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.