"Ronald S. Cook" <rc***@westinis.comwrote in message
news:E8**********************************@microsof t.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 ObtainDataTableFromIEnumerable(IEnumerable ien)
{
DataTable dt = new DataTable();
foreach (object obj in ien)
{
Type t = obj.GetType();
PropertyInfo[] pis = t.GetProperties();
if (dt.Columns.Count == 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;
}