成都网站建设设计

将想法与焦点和您一起共享

DataTable与List<T>互转-创新互联

平时写代码的时候经常会遇到DataTable与List之间的转换操作,由于DataTable数据集合不像List指定了对应的T类型,所以在操作的时候没有List方便,为了方便两个集合的转换,特此写下以下类记录两者之间的互换。

    class ModelConvertHelper where T : new()
{
    /// 
    /// 把DataTable转换成指定类型的List
    /// 
    /// 
    /// 
    public static IList ConvertDataTableToList(DataTable dt)
    {
        // 定义集合    
        IList ts = new List();

        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;
    }

    /// 
    /// 把泛型List转换成DataTable
    /// 
    /// 
    /// 
    public static DataTable ConvertListToDataTable(List list)
    {
        DataTable dt = new DataTable();
        // 获得此模型的公共属性      
        PropertyInfo[] propertys = typeof(T).GetProperties();
        foreach (PropertyInfo pi in propertys)
        {
            // 判断此属性是否有Getter      
            if (!pi.CanRead) continue;
            dt.Columns.Add(pi.Name, pi.PropertyType);
        }
        foreach (T item in list)
        {
            propertys = item.GetType().GetProperties();
            DataRow newRow = dt.NewRow();
            foreach (PropertyInfo pi in propertys)
            {
                if (!pi.CanRead) continue;
                newRow[pi.Name] = pi.GetValue(item);
            }
            dt.Rows.Add(newRow);
        }
        return dt;
    }
}

创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。

专注于为中小企业提供成都网站设计、成都网站制作服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业安宁免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了成百上千企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
名称栏目:DataTable与List<T>互转-创新互联
链接URL:http://chengdu.cdxwcx.cn/article/dijpec.html