---
title: "List转DataTable 反射方式"
author: "send620"
date: "2011-01-19T09:50:00Z"
tags: []
slug: "list-datatable"
draft: false
lastmod: "2011-01-19T09:50:00Z"
id: 901439
url: "https://send620.iteye.com/blog/901439"
---

/// &lt;summary&gt;  
/// 将集合类转换成DataTable  
/// &lt;/summary&gt;  
/// &lt;param name="list"&gt;集合&lt;/param&gt;  
/// &lt;returns&gt;&lt;/returns&gt;  
public static DataTable ToDataTable(IList list)  
{  
DataTable result = new DataTable();  
if (list.Count &gt; 0)  
{  
PropertyInfo\[] propertys = list\[0].GetType().GetProperties();  
foreach (PropertyInfo pi in propertys)  
{  
result.Columns.Add(pi.Name, pi.PropertyType);  
}  
for (int i = 0; i &lt; 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;  
}  
/// &lt;summary&gt;  
/// 将泛型集合类转换成DataTable  
/// &lt;/summary&gt;  
/// &lt;typeparam name="T"&gt;集合项类型&lt;/typeparam&gt;  
/// &lt;param name="list"&gt;集合&lt;/param&gt;  
/// &lt;returns&gt;数据集(表)&lt;/returns&gt;  
public static DataTable ToDataTable&lt;T&gt;(IList&lt;T&gt; list)  
{  
return ConvertX.ToDataTable&lt;T&gt;(list, null);  
}  
/// &lt;summary&gt;  
/// 将泛型集合类转换成DataTable  
/// &lt;/summary&gt;  
/// &lt;typeparam name="T"&gt;集合项类型&lt;/typeparam&gt;  
/// &lt;param name="list"&gt;集合&lt;/param&gt;  
/// &lt;param name="propertyName"&gt;需要返回的列的列名&lt;/param&gt;  
/// &lt;returns&gt;数据集(表)&lt;/returns&gt;  
public static DataTable ToDataTable&lt;T&gt;(IList&lt;T&gt; list, params string\[] propertyName)  
{  
List&lt;string&gt; propertyNameList = new List&lt;string&gt;();  
if (propertyName != null)  
propertyNameList.AddRange(propertyName);  
DataTable result = new DataTable();  
if (list.Count &gt; 0)  
{  
PropertyInfo\[] propertys = list\[0].GetType().GetProperties();  
foreach (PropertyInfo pi in propertys)  
{  
if (propertyNameList.Count == 0)  
{  
result.Columns.Add(pi.Name, pi.PropertyType);  
}  
else  
{  
if (propertyNameList.Contains(pi.Name))  
result.Columns.Add(pi.Name, pi.PropertyType);  
}  
}  
for (int i = 0; i &lt; list.Count; i++)  
{  
ArrayList tempList = new ArrayList();  
foreach (PropertyInfo pi in propertys)  
{  
if (propertyNameList.Count == 0)  
{  
object obj = pi.GetValue(list\[i], null);  
tempList.Add(obj);  
}  
else  
{  
if (propertyNameList.Contains(pi.Name))  
{  
object obj = pi.GetValue(list\[i], null);  
tempList.Add(obj);  
}  
}  
}  
object\[] array = tempList.ToArray();  
result.LoadDataRow(array, true);  
}  
}  
return result;  
}