C# 为具有相同结构和不同列数的类创建扩展方法
我有一个实体框架数据模式,我在其中插入了一些存储过程,并为每个sp创建了一个复杂类型。例如,我的sp 1具有以下复杂类型:C# 为具有相同结构和不同列数的类创建扩展方法,c#,entity-framework,c#-4.0,extension-methods,C#,Entity Framework,C# 4.0,Extension Methods,我有一个实体框架数据模式,我在其中插入了一些存储过程,并为每个sp创建了一个复杂类型。例如,我的sp 1具有以下复杂类型: sp1_result { string c1; string c2; string c3; string c4; } sp2_result { string c1; string c2; } 例如,sp 2具有以下复杂类型: sp1_result { string c1; s
sp1_result
{
string c1;
string c2;
string c3;
string c4;
}
sp2_result
{
string c1;
string c2;
}
例如,sp 2具有以下复杂类型:
sp1_result
{
string c1;
string c2;
string c3;
string c4;
}
sp2_result
{
string c1;
string c2;
}
以此类推。我想将这个复杂结果列表转换为DataTable
,但它们的列数不同,但类型相同。如何为此编写扩展方法
感谢利用反射并创建
数据表
形成对象的列表
集合
/// <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;
}
//
///将IList对象转换为Datatable
///
///类的名称-列表类型
///IList对象
///数据表
公共静态数据表转换器(ILST pList)
{
DataTable=CreateTable();
类型entityType=类型(T);
PropertyDescriptorCollection属性=TypeDescriptor.GetProperties(entityType);
foreach(pList中的T项)
{
DataRow行=table.NewRow();
foreach(属性中的PropertyDescriptor属性)
{
行[prop.Name]=prop.GetValue(项目);
}
table.Rows.Add(行);
}
返回表;
}
非常感谢。但是什么是CreateTable()代码>?我想从我的类列中构建我的数据表应该(IList pList)
转换为(此IList pList)
?@Rozhin-hey方法获取对象列表,即集合并从中生成数据表