首页 > 代码库 > 利用反射将任意元素类型 的 List 转为 DataTable

利用反射将任意元素类型 的 List 转为 DataTable

List to DataTable. 利用反射,将任意元素类型 的 List 转为 DataTable.

Using System.Collections;

Using System.Reflection;

?
public static DataTable ToDataTable(IList list)
{
    DataTable result = new DataTable();
    if (list.Count > 0)
    {
        PropertyInfo[] propertys = list[0].GetType().GetProperties();
        foreach (PropertyInfo pi in propertys)
        {
            result.Columns.Add(pi.Name, pi.PropertyType);
        }
 
        for (int i = 0; i < 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;
}