Hello,
I have an strongly typed DataTable 'MyType', I'd like convert it in an List.
How can I do this ?
Thanks,
Hello,
I have an strongly typed DataTable 'MyType', I'd like convert it in an List.
How can I do this ?
Thanks,
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;
}
Assuming your DataRow
s 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.
The following does it in a single line:
dataTable.Rows.OfType<DataRow>()
.Select(dr => dr.Field<MyType>(columnName)).ToList();