Ienumerable을 데이터 집합으로 변환해야합니다. 이를 위해 모든 IEnumberable 유형을 Dataset으로 변환하기 위해 공통 fnction을 작성해야합니다. 이를 위해 익명 유형을 설정해야합니다..net IEnumberable에 대한 익명 형식을 설정하는 방법
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()
과 같은 코드를 작성할 수 있습니다 : 는 여기가 IList<T>
DataTable
A를 변환이 구현 내 블로그에 문서화 된 코드
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;
}
}
당신은 http://stackoverflow.com – Graviton
아래에 내 대답을 물어 봐야하지만, 당신은 또한 당신이 무엇을 요구하는지 더 정확하게해야합니다. 위에 쓴 내용에는 의문의 여지가 없습니다. 따라서 문제가 무엇인지 알기가 매우 어렵습니다. –