c# Convert list type to DataTable method example

高洛峰
Release: 2017-01-18 09:35:50
Original
1882 people have browsed it

/// <summary>
       /// 将List转换成DataTable
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <param name="data"></param>
       /// <returns></returns>
       public static DataTable ToDataTable<T>(this IList<T> data)
           {
           PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
           DataTable dt = new DataTable();
           for (int i = 0; i < properties.Count; i++)
               {
               PropertyDescriptor property = properties[i];
               dt.Columns.Add(property.Name, 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);
                   }
               dt.Rows.Add(values);
               }
           return dt;
           }
Copy after login

For more c# examples of converting list types into DataTable methods, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!