C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > List类型转换成DataTable

c#将list类型转换成DataTable方法示例

作者:

将List类型转换成DataTable的通用方法,大家参考使用吧

复制代码 代码如下:

/// <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;
           }

您可能感兴趣的文章:
阅读全文