zoukankan      html  css  js  c++  java
  • List<T>转DataTable

       /// <summary>
            /// 生成DataTable
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="collection"></param>
            /// <returns></returns>
            private DataTable ListToDataTable<T>(List<T> collection)
            {
                var dt = new DataTable();
                if (collection.Count <= 0) return dt;
                var props = typeof(T).GetProperties();
                dt.Columns.AddRange(props.Select(p =>
                {
    
                    var colType = p.PropertyType;
                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                    {
                        colType = colType.GetGenericArguments()[0];
                    }
                    var dc = new DataColumn(p.Name, colType);
                    return dc;
                }).ToArray());
    
                for (int i = 0; i < collection.Count; i++)
                {
                    var tempList = new ArrayList();
                    foreach (PropertyInfo pi in props)
                    {
                        object obj = pi.GetValue(collection.ElementAt(i), null);
                        tempList.Add(obj);
                    }
                    var array = tempList.ToArray();
                    dt.LoadDataRow(array, true);
                }
                return dt;
            }
  • 相关阅读:
    P2045 方格取数加强版
    P2774 方格取数问题
    日记——OI历程
    6.30考试
    6.29考试
    数论...
    6.28数论测试
    洛谷P3802 小魔女帕琪
    hosts
    博客设置
  • 原文地址:https://www.cnblogs.com/FH-cnblogs/p/7809019.html
Copyright © 2011-2022 走看看