tags:

views:

694

answers:

1

Hi. I have a (disconnected) typed Dataset in an XML, which I query in LINQ:

var productlist = from prds in dsProducts.Products.AsEnumerable()
where (prds.Field<string>("productid").Contains(searchpattern) || 
       prds.Field<string>("productname").Contains(searchpattern))
select prds;

This list is fine, but if I try to say:

return (DataSetProducts.productsDataTable)productlist.Skip(begin).Take(pagesize).CopyToDataTable();

It says it can not convert System.DataTable to DataSetProducts.productsDataTable, however it is the same table.

Any thoughts on how to return a typed DataTable?

+2  A: 

Well, CopyToDataTable has no way of knowing what is the correct strong DataTable type for a given type of DataRow, since the DataRow doesn't provide that information (which is a shame IMHO).

Perhaps you could write your own CopyToDataTable method, which would take another type parameter to specify the table type. Something like that :

public static TTable CopyToDataTable<TRow, TTable>(this IEnumerable<TRow> rows)
  where TRow : DataRow, new()
  where TTable : DataTable, new()
{
    TTable table = new TTable();
    foreach (TRow row in rows)
    {
        TRow rowCopy = new TRow();
        object[] itemArrayCopy = new object[row.ItemArray.Length];
        row.ItemArray.CopyTo(itemArrayCopy, 0);
        rowCopy.ItemArray = itemArrayCopy;
        table.Rows.Add(rowCopy);
    }
    return table;
}

EDIT :

how can I use this new function in the above example?

You must put this extension method in a static class. If you put the class in a different namespace, make sure to import that namespace in the scope with a using clause.

You can then use the method like that (you must specify the type parameters since the TTable type can't be inferred by the compiler) :

return productlist.Skip(begin).Take(pagesize).CopyToDataTable<DataSetProducts.productsRow, DataSetProducts.productsDataTable>();

Please note that I didn't test this code, there might be a few bugs...

Thomas Levesque
Wery nice workaround, thank you. One question for the dummies like me: how can I use this new function in the above example?
balint
See my updated answer
Thomas Levesque