我需要将Ienumerable转换为数据集。为此,我需要编写一个通用功能来将任何IEnumberable类型转换为Dataset。为此,我需要设置匿名类型。 这是代码
public static DataTable ToDataTable(Object alist)
{
String AssemblyName = "DataAccessLayer";
String ClassName = "sptblSystemPreference_GetListResult";
Type ObjType = Type.GetType(ClassName + "," + AssemblyName);
//Below line working fine... But how can i implement ObjType in the IEnumberable
IEnumerable<DataAccessLayer.sptblSystemPreference_GetListResult> objList1 = (IEnumerable<DataAccessLayer.sptblSystemPreference_GetListResult>)alist;
List<DataAccessLayer.sptblSystemPreference_GetListResult> objList = objList1.ToList();
DataTable dt = new DataTable();
if (objList[0] != null)
{
dt.TableName = objList[0].GetType().Name;
System.Reflection.PropertyInfo[] propInfo = objList[0].GetType().GetProperties();
for (int PropertyCount = 0; PropertyCount < propInfo.Length; PropertyCount++)
{
dt.Columns.Add(propInfo[PropertyCount].Name);
}
for (int row = 0; row < objList.Count; row++)
{
DataRow dr;
dr = dt.NewRow();
for (int PropertyCount = 0; PropertyCount < propInfo.Length; PropertyCount++)
{
Object obj = propInfo[PropertyCount].GetValue(objList[row], null);
if(obj!=null)
dr[PropertyCount] = obj;
}
dt.Rows.Add(dr);
}
}
return dt;
}
}
答案 0 :(得分:1)
我实施此操作是为了将IList<T>
转换为DataTable
并将其记录在我的博客上:
public static class ListExtensions
{
public static DataTable ToDataTable<T>(this IList<T> list)
{
IList<PropertyInfo> properties = list.GetPropertiesOfObjectInList();
DataTable resultTable = CreateTable(properties);
foreach(var item in list)
{
var row = CreateRowFromItem<T>(resultTable, item);
resultTable.Rows.Add(row);
}
return resultTable;
}
private static DataTable CreateTable(IList<PropertyInfo> properties)
{
DataTable resultTable = new DataTable();
foreach (var property in properties)
{
resultTable.Columns.Add(property.Name, property.PropertyType);
}
return resultTable;
}
public static IList<PropertyInfo> GetPropertiesOfObjectInList<T>(this IList<T> list)
{
return typeof(T).GetProperties().ToList();
}
private static DataRow CreateRowFromItem<T>(DataTable resultTable, T item)
{
var row = resultTable.NewRow();
var properties = item.GetType().GetProperties().ToList();
foreach (var property in properties)
{
row[property.Name] = property.GetValue(item, null);
}
return row;
}
}
这允许您编写像DataTable yourTable = yourList.ToDataTable()
这样的代码。您可以在此处阅读:Generic list to DataTable