首页 > Windows开发 > 详细

【C#通用功能】1.DataTable与List<T>等集合互转

时间:2019-11-01 15:18:06      阅读:64      评论:0      收藏:0      [点我收藏+]

 


 

DataTable与List<T>互转

1.List<T>转DataTable


 

public static DataTable ListToDataTable<T>(List<T> list)
{
    if(list==null || list.Count==0)
    {
        return new DataTable();
    }
    //获取T下所有的属性
    Type entityType = list[0].GetType();
    PropertyInfo[] entityProperties = entityType.GetProperties();

    DataTable dt = new DataTable("data");
    for(int i=0; i<entityProperties.Length; i++)
    {
        dt.Columns.Add(entityProperties[i].Name);
    }
    foreach (var item in list)
    {
        if(item.GetType() != entityType)
        {
            throw new Exception("要转换集合元素类型不一致!")
        }
        //创建一个用于放所有属性值的数组
        object[] entityValues = new object[entityProperties.Length];
        for(int i=0; i<entityProperties.Length; i++)
        {
            entityValues[i] = entityProperties[i].GetValue(item, null);
        }
        
        dt.Rows.Add(entityValues)
    }
    return dt;
}

 

2.DataTable转List<T>


 

public static IList<T> ConvertToModel(DataTable dt)    
{    
   // 定义集合    
    IList<T> ts = new List<T>(); 
   // 获得此模型的类型   
    Type type = typeof(T);      
   string tempName = "";      
   foreach (DataRow dr in dt.Rows)      
    {    
        T t = new T();     
       // 获得此模型的公共属性      
        PropertyInfo[] propertys = t.GetType().GetProperties(); 
       foreach (PropertyInfo pi in propertys)      
        {      
            tempName = pi.Name;  // 检查DataTable是否包含此列   
           if (dt.Columns.Contains(tempName))      
            {      
               // 判断此属性是否有Setter      
               if (!pi.CanWrite) continue;        
               object value = dr[tempName];      
               if (value != DBNull.Value)      
                    pi.SetValue(t, value, null);  
            }     
        }      
        ts.Add(t);      
    }     
   return ts;     
}     

 

【C#通用功能】1.DataTable与List<T>等集合互转

原文:https://www.cnblogs.com/512kd/p/11776818.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!