Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query on DataTable - Could not find an implementation of the query pattern

Tags:

c#

linq

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();
        }
    }
}
like image 918
user1480480 Avatar asked Dec 05 '22 15:12

user1480480


1 Answers

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.

like image 127
Magnus Avatar answered Dec 10 '22 11:12

Magnus