using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
///
/// 雷怡 2021-08-17
/// TableData List 互转
///
public static class DTList
{
///
/// DataTable转换成List
///
///
///
///
public static List ConvertToList(DataTable table)
{
List list = new List();
T t = default(T);
PropertyInfo[] propertypes = null;
string tempName = string.Empty;
foreach (DataRow row in table.Rows)
{
t = Activator.CreateInstance();
propertypes = t.GetType().GetProperties();
foreach (PropertyInfo pro in propertypes)
{
tempName = pro.Name;
if (table.Columns.Contains(tempName))
{
object value = row[tempName];
if (!value.ToString().Equals(""))
{
pro.SetValue(t, value, null);
}
}
}
list.Add(t);
}
return list.Count == 0 ? null : list;
}
///
/// List转换成DataTable
///
///
/// 实例化当前list 的list集合
/// 集合数据
/// 返回DataTable
public static System.Data.DataTable ToDataTable(this System.Collections.Generic.IList list, System.Collections.Generic.IList dataList) where T : class, new()
{
if (dataList == null || !dataList.Any())
{
return null;
}
Type type = typeof(T);
System.Data.DataTable dt = new System.Data.DataTable(type.Name);
System.Reflection.PropertyInfo[] propertyInfoArray = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
foreach (T t in dataList.Where(t => t != null))
{
System.Data.DataRow row = dt.NewRow();
for (int i = 0, j = propertyInfoArray.Length; i < j; i++)
{
System.Reflection.PropertyInfo propertyInfo = propertyInfoArray[i];
string name = propertyInfo.Name;
if (dt.Columns[name] == null)
{
System.Data.DataColumn column = new System.Data.DataColumn(name, propertyInfo.PropertyType);
dt.Columns.Add(column);
}
row[name] = propertyInfo.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}
}
}