zoukankan      html  css  js  c++  java
  • 译:泛型List集合转化为DateTable的扩展方法

    译文出处:http://www.codeproject.com/Tips/867866/Extension-Method-for-Generic-List-Collection-to-Da

    这段代码是能够帮助你把泛型集合List转出成DataTable的扩展方法。

    背景:

    不知道你是否知道这个扩展方法,但是你可以不做任何修改的去使用下面这个类的代码。

    使用代码:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    
    namespace coDEalers
    {
        public static class Extension
        {
            public static DataTable ListToDataTable<T>(this IList<T> data, string tableName)
            {
                DataTable table = new DataTable(tableName);
    
                //special handling for value types and string
                if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
                {
    
                    DataColumn dc = new DataColumn("Value");
                    table.Columns.Add(dc);
                    foreach (T item in data)
                    {
                        DataRow dr = table.NewRow();
                        dr[0] = item;
                        table.Rows.Add(dr);
                    }
                }
                else
                {
                    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
                    foreach (PropertyDescriptor prop in properties)
                    {
                        table.Columns.Add(prop.Name, 
                        Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
                    }
                    foreach (T item in data)
                    {
                        DataRow row = table.NewRow();
                        foreach (PropertyDescriptor prop in properties)
                        {
                            try
                            {
                                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                            }
                            catch (Exception ex)
                            {
                                row[prop.Name] = DBNull.Value;
                            }
                        }
                        table.Rows.Add(row);
                    }
                }
                return table;
            }
        }
    }

    优点(兴趣点):

    这是一个把GenericList集合转化成DataTable的一个简单的方法。

    用法:

    DataTable dt = null;
    List<StateList> stateListObj = JsonConvert.DeserializeObject<List<StateList>>(hdn_stateDetails_JSON.Value);
    dt = stateListObj.ListToDataTable<StateList>("dtState");

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  • 相关阅读:
    CentOS 7 虚拟机的安装
    2 MySQL rpm
    01-在实体类上加了lombok的@Data注解
    02-myBatisPlus的wrapper接口的使用
    2 MySQL rpm 安装 --下载
    1-MySQL介绍
    MySQL的不归路
    电脑型号4 1500 内存大 机械大硬盘
    电脑型号3 1200 大硬盘
    电脑概览 2 1200 固态SSD
  • 原文地址:https://www.cnblogs.com/yplong/p/4266455.html
Copyright © 2011-2022 走看看