将List转换成DataTable

时间:2023-03-08 23:45:50
将List转换成DataTable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using YTO.WeiXin.Model;
using System.Collections; namespace WeiXin.Core
{
public class ListToDataTable
{
public static DataTable ToDataTable<T>(IList<T> list)
{
return ToDataTable(list, null);
} //将list转换成DataTable
public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
{
List<string> propertyNameList = new List<string>();
if (propertyName != null)
{
propertyNameList.AddRange(propertyName);
}
DataTable result = new DataTable();
if (list.Count > )
{
PropertyInfo[] propertys = list[].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == )
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
else
{
if (propertyNameList.Contains(pi.Name))
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
}
}
for (int i = ; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == )
{
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;
} //AuthorizationInfo 将DataTable转换成list
public static IList<AuthorizationInfo> ToList(DataTable dt, IList<AuthorizationInfo> list1)
{
//IList<AuthorizationInfo> list1 = new List<AuthorizationInfo>();
for (int i = ; i < dt.Rows.Count; i++)
{
AuthorizationInfo authInfo = new AuthorizationInfo();
authInfo.Id = (dt.Rows[i].ItemArray[]).ToString();
authInfo.LiencePlateNumber = (dt.Rows[i].ItemArray[]).ToString();
authInfo.Bar_code = (dt.Rows[i].ItemArray[]).ToString();
authInfo.PhoneNumber = (dt.Rows[i].ItemArray[]).ToString();
authInfo.OpenId = (dt.Rows[i].ItemArray[]).ToString();
authInfo.CreateTime = Convert.ToDateTime(dt.Rows[i].ItemArray[]);
authInfo.Status = (dt.Rows[i].ItemArray[]).ToString();
list1.Add(authInfo);
}
return list1;
} //将ExcptionInfo DataTable转换成list
public static IList<ExcptionInfo> ToList(DataTable dt, IList<ExcptionInfo> list1)
{
//IList<ExcptionInfo> list1 = new List<ExcptionInfo>();
for (int i = ; i < dt.Rows.Count; i++)
{
ExcptionInfo exInfo = new ExcptionInfo();
exInfo.Id = (dt.Rows[i].ItemArray[]).ToString();
exInfo.LiencePlateNumber = (dt.Rows[i].ItemArray[]).ToString();
exInfo.CarLine = (dt.Rows[i].ItemArray[]).ToString();
exInfo.PhoneNumber = (dt.Rows[i].ItemArray[]).ToString();
exInfo.OpenId = (dt.Rows[i].ItemArray[]).ToString();
exInfo.CreateTime = Convert.ToDateTime(dt.Rows[i].ItemArray[]);
exInfo.Remark = (dt.Rows[i].ItemArray[]).ToString();
exInfo.ExcptionCategory = (dt.Rows[i].ItemArray[]).ToString();
exInfo.Position = (dt.Rows[i].ItemArray[]).ToString();
list1.Add(exInfo);
}
return list1;
}
}
}