using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
namespace ClassLibrary1 {
public class DataConvert {
/// <summary>
/// DataTable转换List<T>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> TableToList<T>(DataTable dt) {
List<T> ret = new List<T>();
Type type = typeof(T);
List<string> lstColumns = new List<string>();
foreach (DataRow dr in dt.Rows) {
PropertyInfo[] proInfo = type.GetProperties();
T entity = Activator.CreateInstance<T>();
foreach (PropertyInfo p in proInfo) {
if (!dt.Columns.Contains(p.Name) || dr[p.Name] == null || dr[p.Name] == DBNull.Value)
continue;
if (p.PropertyType == typeof(DateTime) && Convert.ToDateTime(dr[p.Name]) < Convert.ToDateTime("1753-01-01"))
continue;
try {
object obj = Convert.ChangeType(dr[p.Name], p.PropertyType);
p.SetValue(entity, obj, null);
} catch {
}
}
ret.Add(entity);
}
return ret;
}
/// <summary>
/// List<T>转换DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ListToTable<T>(List<T> list) {
Type type = typeof(T);
PropertyInfo[] proInfo = type.GetProperties();
DataTable dt = new DataTable();
foreach (PropertyInfo p in proInfo) {
//类型存在Nullable<Type>时,需要进行以下处理,否则异常
Type t = p.PropertyType;
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
t = t.GetGenericArguments()[0];
dt.Columns.Add(p.Name, t);
}
foreach (T t in list) {
DataRow dr = dt.NewRow();
foreach (PropertyInfo p in proInfo) {
object obj = p.GetValue(t);
if (obj == null) continue;
if (p.PropertyType == typeof(DateTime) && Convert.ToDateTime(obj) < Convert.ToDateTime("1753-01-01"))
continue;
dr[p.Name] = obj;
}
dt.Rows.Add(dr);
}
return dt;
}
public static T TableRowToEntity<T>(DataTable dt,int rowIndex) {
Type type = typeof(T);
T entity = Activator.CreateInstance<T>();
if (dt == null) return entity;
DataRow dr = dt.Rows[rowIndex];
PropertyInfo[] proInfo = type.GetProperties();
foreach (PropertyInfo p in proInfo) {
if (!dt.Columns.Contains(p.Name) || dr[p.Name] == null || dr[p.Name] == DBNull.Value)
continue;
if (p.PropertyType == typeof(DateTime) && Convert.ToDateTime(dr[p.Name]) < Convert.ToDateTime("1753-01-01"))
continue;
try {
object obj = Convert.ChangeType(dr[p.Name], p.PropertyType);
p.SetValue(entity, obj, null);
} catch{
}
}
return entity;
}
}
}
List、DataTable和对象互转,List转DataTable异常Nullable解决方案
最新推荐文章于 2024-07-09 17:28:16 发布