zoukankan      html  css  js  c++  java
  • C# List转换成DataTable

            /// <summary>
            /// C# List转换成DataTable
            /// </summary>
            /// <param name="list"></param>
            /// <returns></returns>
            public static System.Data.DataTable ListToDataTable(IList list)
            {
                System.Data.DataTable result = new System.Data.DataTable();
                if (list.Count > 0)
                {
                    PropertyInfo[] propertys = list[0].GetType().GetProperties();
                    foreach (PropertyInfo pi in propertys)
                    {
                        //获取类型
                        Type colType = pi.PropertyType;
                        //当类型为Nullable<>时
                        if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                        {
                            colType = colType.GetGenericArguments()[0];
                        }
                        result.Columns.Add(pi.Name, colType);
                    }
                    for (int i = 0; i < list.Count; i++)
                    {
                        ArrayList tempList = new ArrayList();
                        foreach (PropertyInfo pi in propertys)
                        {
                            object obj = pi.GetValue(list[i], null);
                            tempList.Add(obj);
                        }
                        object[] array = tempList.ToArray();
                        result.LoadDataRow(array, true);
                    }
                }
                return result;
            }
  • 相关阅读:
    团队开发-第一阶段冲刺-10
    团队开发-第一阶段冲刺-09
    Spring(三)
    第五周总结
    Spring(一)
    程序员修炼之道:从小工到专家阅读笔记1
    MyBatis(三)
    MyBatis(二)
    MyBatis
    第四周总结
  • 原文地址:https://www.cnblogs.com/hong01072/p/12944302.html
Copyright © 2011-2022 走看看