将泛型集合转换为datatable
/**/
/// <summary>
/// 将泛型集合类转换成DataTable
/// </summary>
/// <typeparam name="T">集合项类型</typeparam>
/// <param name="list">集合</param>
/// <returns>数据集(表)</returns>
public static DataTable ToDataTable<T>(List<T> list)
{
return ListToDataTable<T>(list);
}
/// <summary>
/// 将泛类型集合List类转换成DataTable
/// </summary>
/// <param name="list">泛类型集合</param>
/// <returns></returns>
public static DataTable ListToDataTable<T>(List<T> entitys)
{
//检查实体集合不能为空
if (entitys == null || entitys.Count < 1)
{
throw new Exception("需转换的集合为空");
}
//取出第一个实体的所有Propertie
//Type entityType = entitys[0].GetType();
PropertyInfo[] entityProperties = entitys[0].GetType().GetProperties();
//生成DataTable的structure
//生产代码中,应将生成的DataTable结构Cache起来,此处略
DataTable dt = new DataTable("temp");
for (int i = 0; i < entityProperties.Length; i++)
{
//dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
dt.Columns.Add(entityProperties[i].Name);
}
//将所有entity添加到DataTable中
foreach (object entity in entitys)
{
检查所有的的实体都为同一类型
//if (entity.GetType() != entityType)
//{
// throw new Exception("要转换的集合元素类型不一致");
//}
object[] entityValues = new object[entityProperties.Length];
for (int i = 0; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null);
}
dt.Rows.Add(entityValues);
}
return dt;
}
调用
List<实体类> list=new List<实体类>();
DataTable dt=ToDataTable(list);
datatable转泛型集合
第一种
//拿到数据
string sql = "select * from T_ExcelIn";
DataTable table= SqlHelper.GetDataTable(sqlcon,CommandType.Text,sql,null);
//序列化为字符串
string t = JsonConvert.SerializeObject(table);
//反序列化为对象
List<ExcelIn> ex= JsonConvert.DeserializeObject<List<ExcelIn>>(t);
第二种
//调用
DataTable Accdt = help.ExcuteQuery("SqlServer", sqlStr);
List<要转成的实体> listqwe = ConvertToModel<要转成的实体>(Accdt);
/// <summary>
/// datable转list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <summary>
/// 利用反射和泛型
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ConvertToModel<T>(DataTable dataTable) where T : new()
{
//定义一个泛型集合
List<T> genericCollectionsList = new List<T>();
//获得此模型的类型
Type type = typeof(T);
//定义一个临时的变量
string tempName = "";
//遍历dataTable中所有数据行
foreach (DataRow dataRow in dataTable.Rows)
{
dynamic modelType = new T();
//获得此模型的公共属性
PropertyInfo[] propertys = modelType.GetType().GetProperties();
//遍历所有属性
foreach (PropertyInfo propertyInfo in propertys)
{
//将此属性赋值给临时变量
tempName = propertyInfo.Name;
//检查datatable是否包含此列
if (dataTable.Columns.Contains(tempName))
{
//判断此属性是否有setter,这个啥意思呢,就是我们的实体层的{get;set;}如果我们的实体有了set方法,就说明可以赋值!
if (!propertyInfo.CanWrite) continue;
{
//取值
object value = dataRow[tempName];
if (value != DBNull.Value)
propertyInfo.SetValue(modelType, value, null);
}
}
}
//对象添加到泛型集合中
genericCollectionsList.Add(modelType);
}
return genericCollectionsList;
}