일반 유형에서 DataTable 유형으로 전환

2203 단어 Datatable
     public static DataTable ConvertToDatatable<T>(IEnumerable<T> data)

        {

            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));

            DataTable table = new DataTable();



            for (int i = 0; i < props.Count; i++)

            {

                PropertyDescriptor prop = props[i];

                //table.Columns.Add(prop.Name, prop.PropertyType);// !DataSet   System.Nullable<>。

                //  DataColumn   Nullable<T>  , DBNull。

                table.Columns.Add(prop.Name);

            }



            object[] values = new object[props.Count];



            foreach (T item in data)

            {

                for (int i = 0; i < values.Length; i++)

                {

                    values[i] = props[i].GetValue(item);

                }

                table.Rows.Add(values);

            }

            return table;

        }

좋은 웹페이지 즐겨찾기