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");

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

  • 相关阅读:
    学生数据增删改查--顺序表
    应用3+2mvc第一次作业
    双色球随机选【代码】
    字符串穷举
    使用nuget发布自己的包
    VS CODE中配置JAVA格式化细节
    反射的理解(含一点xml)
    UdpClient实现udp消息收发
    c#背包问题代码
    利用TcpClient,简单的tcp消息收发
  • 原文地址:https://www.cnblogs.com/yplong/p/4266455.html
Copyright © 2011-2022 走看看