gpt4 book ai didi

c# - 将 DataTable 转换为 List (ProjectDracula)

转载 作者:行者123 更新时间:2023-11-30 23:34:12 25 4
gpt4 key购买 nike

我需要一个静态方法来将数据表(动态)转换为列表(再次是动态实体)这是我的代码帮助将不胜感激

        public static ICollection<System.Data.Entity.Core.Objects.DataClasses.EntityObject> DtToEntity(DataTable DataTable,System.Data.Entity.Core.Objects.DataClasses.EntityObject EntityObject)
{
ICollection<System.Data.Entity.Core.Objects.DataClasses.EntityObject> _list = null;
System.Data.Entity.Core.Objects.DataClasses.EntityObject _tempClass;
foreach (DataRow dataRow in DataTable.Rows)
{
foreach(DataColumn dataColumn in DataTable.Columns)
{
foreach (var attribute in EntityObject.GetType().GetProperties())
{
if (attribute.Name == dataColumn.ColumnName && attribute.GetType().Equals(dataColumn.GetType()))
{
return _list;
}
}
}


}

最佳答案

private static List<T> ConvertDataTable<T>(DataTable dt)  
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
T item = GetItem<T>(row);
data.Add(item);
}
return data;
}

private static T GetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();

foreach (DataColumn column in dr.Table.Columns)
{
foreach (PropertyInfo pro in temp.GetProperties())
{
if (pro.Name == column.ColumnName)
pro.SetValue(obj, dr[column.ColumnName], null);
else
continue;
}
}
return obj;
}

用法:

List< Student > studentDetails = new List<Student>();  
studentDetails = ConvertDataTable<Student>(dt);

来源:http://www.c-sharpcorner.com/UploadFile/ee01e6/different-way-to-convert-datatable-to-list/

关于c# - 将 DataTable 转换为 List<Entity> (ProjectDracula),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33515552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com