zoukankan      html  css  js  c++  java
  • C#--List转DataTable(或DataSet)

    /// <summary>
            /// List转DataTable
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="data"></param>
            /// <returns></returns>
            public static DataSet ListToDataTable<T>(List<T> data)
            {
                DataSet ds = new DataSet();
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
                DataTable dataTable = new DataTable();
                for (int i = 0; i < properties.Count; i++)
                {
                    PropertyDescriptor property = properties[i];
                    dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
                }
                object[] values = new object[properties.Count];
                foreach (T item in data)
                {
                    for (int i = 0; i < values.Length; i++)
                    {
                        values[i] = properties[i].GetValue(item);
                    }
    
                    dataTable.Rows.Add(values);
                }
                ds.Tables.Add(dataTable);
                return ds;
            }
  • 相关阅读:
    04-JQuery
    03-JavaScript
    02-CSS&JS
    01-HTML
    [LeetCode]Insert Interval
    [shell编程]正则表达式
    [LeetCode]Jump Game II
    [LeetCode]Jump Game
    [LeetCode]Wildcard Matching
    [shell编程]初识sed和gawk
  • 原文地址:https://www.cnblogs.com/dcy521/p/11413187.html
Copyright © 2011-2022 走看看