Im folgenden hab ich mal einen kleinen Codeschnippsel zusammengestellt, wie er immer mal wieder gebraucht wird. Dabei soll eine Liste von beliebigen Datentypen in eine Datatable gemappt werden.
public DataTable Transform(List structList)
{
DataTable dt = new DataTable();
if (structList.Count <= 0) return null;
//read Structure from item
IEnumerator enumerator = structList.GetEnumerator();
Type itemType = enumerator.Current.Value.GetType();
PropertyInfo[] pi = itemType.GetProperties();
dt.TableName = itemType.Name;
foreach (PropertyInfo propinfo in pi)
{
dt.Columns.Add(propinfo.Name, propinfo.PropertyType);
}
try
{
foreach (object item in structList)
{
object[] row = new object[pi.Length];
for (int i = 0; i < pi.Length; i++)
{
PropertyInfo propinfo = (PropertyInfo)pi.GetValue(i);
if (item.GetType().GetProperty(propinfo.Name).GetValue(item, null) == null) continue;
row[i] = item.GetType().GetProperty(propinfo.Name).GetValue(item, null);
}
dt.Rows.Add(row);
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return dt;
}