我有一个实体框架数据模式,我将其插入到一些存储过程中,并且对于每个SP,我创建了一个复杂类型。例如,我的sp 1具有这种复杂类型:
sp1_result
{
string c1;
string c2;
string c3;
string c4;
}
例如sp 2具有这种复杂类型:
sp2_result
{
string c1;
string c2;
}
依此类推。我想将此复杂结果的List转换为DataTable
,但它们的列数不同,但它们的类型相同。我怎么能为此写一个Extension Method
?
感谢
答案 0 :(得分:2)
利用反射并创建DataTable
形成对象的List
集合...
/// <summary>
/// Converts IList object to Datatable
/// </summary>
/// <typeparam name="T"> name of the class - List Type</typeparam>
/// <param name="pList"> IList object</param>
/// <returns>Datatable</returns>
public static DataTable ConvertTo<T>(IList<T> pList)
{
DataTable table = CreateTable<T>();
Type entityType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (T item in pList)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
table.Rows.Add(row);
}
return table;
}