zoukankan      html  css  js  c++  java
  • .NET C# 泛型集合转DataTable

    1.功能类

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;

    namespace Infrastructure
    {
        public static class EnumerableExtensions
        {
            public static DataTable CopyToDataTable<T>(this IEnumerable<T> array)
            {
                DataTable result = new DataTable();
                foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof (T)))
                {
                    if (pd.PropertyType.IsGenericType && pd.PropertyType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))
                        result.Columns.Add(pd.Name,Nullable.GetUnderlyingType(pd.PropertyType));
                    else
                        result.Columns.Add(pd.Name, pd.PropertyType);
                }
                foreach (T item in array)
                {
                    DataRow row = result.NewRow();
                    foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(T)))
                        row[pd.Name] = pd.GetValue(item) ?? DBNull.Value;
                    result.Rows.Add(row);
                }
                return result;
            }
        }
    }
    2.调用方式

    List<T> items = new List<T>();

    xxx //为items赋值

    DataTable dataTable = EnumerableExtensions.CopyToDataTable(items);//调用方法

  • 相关阅读:
    android UI 适配小节
    Android中的倒计时实现
    几种适配器&观察者&ListView之间的那点事
    Service stopSelf(int statId)和onStartcommand(Intent intent,int flags,int startId)
    java 虚函数
    java 重载和多态的区别
    小程序体验版路径以及参数携带
    微信小程序--上传图片公用组件
    微信小程序页面返回
    js兼容安卓和IOS的复制文本到剪切板
  • 原文地址:https://www.cnblogs.com/jeff151013/p/11739359.html
Copyright © 2011-2022 走看看