zoukankan      html  css  js  c++  java
  • 【C#常用方法】1.DataTable与List<T>的相互转换

     


     

    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;     
    }     
  • 相关阅读:
    Qt 读写XML文件
    用 Qt 中的 QDomDocument类 处理 XML 文件(上)
    Qss
    QTableWidget的使用和美工总结
    用 Qt 中的 QDomDocument类 处理 XML 文件(下)
    ArcEngine中最短路径的实现
    AE中网络分析的实现 的各个类之间的关系
    AE控制图层中要素可见状态的几种方法
    如何使用Name对象,包括WorkspaceNames和DatasetNames
    AE属性表操作
  • 原文地址:https://www.cnblogs.com/512kd/p/11776818.html
Copyright © 2011-2022 走看看