views:

1815

answers:

3

Hello,

I have an strongly typed DataTable 'MyType', I'd like convert it in an List.

How can I do this ?

Thanks,

+1  A: 

There are Linq extension methods for DataTable.

Add reference to: System.Data.DataSetExtensions.dll

Then include the namespace: using System.Data.DataSetExtensions

Finally you can use Linq extensions on DataSet and DataTables:

var matches = myDataSet.Tables.First().Where(dr=>dr.Field<int>("id") == 1);

On .Net 2.0 you can still add generic method:

public static List<T> ConvertRowsToList<T>( DataTable input, Convert<DataRow, T> conversion) {
    List<T> retval = new List<T>()
    foreach(DataRow dr in input.Rows)
        retval.Add( conversion(dr) );

    return retval;
}
Keith
Is there an easy way if stuck using .NET 2.0?
auujay
+1  A: 

Assuming your DataRows inherit from your own type, say MyDataRowType, this should work:

List<MyDataRowType> list = new List<MyDataRowType>();

foreach(DataRow row in dataTable.Rows)
{
    list.Add((MyDataRowType)row);
}

This is assuming, as you said in a comment, that you're using .NET 2.0 and don't have access to the LINQ extension methods.

Adam Robinson
why not just make a List<DataRow>
Mike Blandford
@Mike: Since the OP says he has a strongly-typed DataTable, I would assume he would prefer to keep that strong typing in his results.
Adam Robinson
@Adam, yes I'd like keep the strong typing. I have access to Linq now in this project
Kris-I
+1  A: 

The following does it in a single line:

dataTable.Rows.OfType<DataRow>()
    .Select(dr => dr.Field<MyType>(columnName)).ToList();
Yuriy Faktorovich