"Ronald S. Cook" <rcook@westinis .comwrote in message
news:E821C5DE-43C0-4B38-B530-54A38A2C669D@mi crosoft.com...
Does anyone know how to convert an object of type IEnumerable to a
DataTable?
There is no automatic way. You will have to iterate on the contents of the
IEnumerable in a loop, and then add each object returned by the enumerator
to a new DataRow in the DataTable. Of course, this raises the question of
"what kind of table and which columns should it have". If you want to do it
in a general way that will be valid for any IEnumerable, you will have to
use Reflection on the returned objects to find out their properties (or
fields) and then create a datatable with columns of the same type, and then
use Reflection again to get the values and add them to the columns of each
row.
private DataTable ObtainDataTable FromIEnumerable (IEnumerable ien)
{
DataTable dt = new DataTable();
foreach (object obj in ien)
{
Type t = obj.GetType();
PropertyInfo[] pis = t.GetProperties ();
if (dt.Columns.Cou nt == 0)
{
foreach (PropertyInfo pi in pis)
{
dt.Columns.Add( pi.Name, pi.PropertyType );
}
}
DataRow dr = dt.NewRow();
foreach (PropertyInfo pi in pis)
{
object value = pi.GetValue(obj , null);
dr[pi.Name] = value;
}
dt.Rows.Add(dr) ;
}
return dt;
}
Thanks. To then update the database, I guess you can't somehow iterate over
the DataTable and recreate the IEnumerable, huh? How then would yoiu update
the database?
"Ronald S. Cook" <rcook@westinis .comwrote in message
news:E821C5DE-43C0-4B38-B530-54A38A2C669D@mi crosoft.com...
>Does anyone know how to convert an object of type IEnumerable to a
>DataTable?
>
There is no automatic way. You will have to iterate on the contents of the
IEnumerable in a loop, and then add each object returned by the enumerator
to a new DataRow in the DataTable. Of course, this raises the question of
"what kind of table and which columns should it have". If you want to do
it in a general way that will be valid for any IEnumerable, you will have
to use Reflection on the returned objects to find out their properties (or
fields) and then create a datatable with columns of the same type, and
then use Reflection again to get the values and add them to the columns of
each row.
>
private DataTable ObtainDataTable FromIEnumerable (IEnumerable ien)
{
DataTable dt = new DataTable();
foreach (object obj in ien)
{
Type t = obj.GetType();
PropertyInfo[] pis = t.GetProperties ();
if (dt.Columns.Cou nt == 0)
{
foreach (PropertyInfo pi in pis)
{
dt.Columns.Add( pi.Name, pi.PropertyType );
}
}
DataRow dr = dt.NewRow();
foreach (PropertyInfo pi in pis)
{
object value = pi.GetValue(obj , null);
dr[pi.Name] = value;
}
dt.Rows.Add(dr) ;
}
return dt;
}
>
Comment