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

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

  • 相关阅读:
    Python实现DES加密算法
    空循环,g++ O2优化
    java 高并发下超购问题解决
    原型模式
    Lambda速学
    观察者模式
    略读策略模式
    .net 字典的速学
    执行计划准备篇
    关于“策略模式”与“桥接模式”的问题
  • 原文地址:https://www.cnblogs.com/yplong/p/4266455.html
Copyright © 2011-2022 走看看