欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-19 21:42:16
复制代码 代码如下:///        /// 将list转换成datatabl...

复制代码 代码如下:

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