Search code examples
c#linqado.netlinq-to-dataset

'select new' doesn't work in LINQ to DataSet.CopyToDataTable()


In the following link: http://msdn.microsoft.com/en-us/library/bb386921.aspx

"Creating a Custom CopyToDataTable Method" Paragraph > Example

I tried to do something similar. This is my code:

ObjDA = new OleDbDataAdapter(querySQL, conection);

//Create a DataSet object:
ObjDS = new DataSet();

ObjDA.Fill(ObjDS, "Table1");

DataTable MyTable = ObjDS.Tables["Table1"];

//IEnumerable<DataRow> query =
var query =
    from user in MyTable.AsEnumerable()
    where user.Field<string>("Name").StartsWith("c", true, null)
    select new
    {
        Name = user.Field<string>("Name")
    };

DataTable orderTable = query.CopyToDataTable();

The issue is in "query.CopyToDataTable": There isn't an implicit reference conversion "AnonymoustType#1" to "System.Data.DataRow". If I write "select user", it works ok but the problem is: select new.

If I write:

query = (...) as IEnumerable<DataRow>

query always return null.

I don't know what to do.


Solution

  • Did you actually follow the procedure that is described in the article? As the article explains, CopyToDataTable by default only works on an IEnumerable<DataRow>. If you want to use the method on a custom type you need to Implement CopyToDataTable Where the Generic Type T Is Not a DataRow

    All of the examples in that section assume you have followed the process and created the custom CopyToDataTable<T> method first.