DataTable转换成IList(二)

简介:

作者:陈太汉

DataTable转换成IList(二)

DataTable转换成IList第一版出来之后,昨晚总是觉得有很多地方可以改进,所以今天一大早来就把它给修订了,当然还有一些地方可以改进,等我以后编码能力提高之后再出第三版吧,第二版应该够用

 

复制代码
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Collections;
using System.Data;

namespace JSONTest
{
public class TableToList<T> where T : new()
{
/// <summary>
/// DataTable转换成IList
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public IList<T> ToList(DataTable dt)
{
if (dt == null || dt.Rows.Count == 0)
{
return null;
}

PropertyInfo[] properties
= typeof(T).GetProperties();//获取实体类型的属性集合
IList<string> colNames = GetColumnNames(dt.Columns);//按照属性顺序的列名集合
List<T> list = new List<T>();
T model
= default(T);
foreach (DataRow dr in dt.Rows)
{
model
= new T();//创建实体
int i = 0;
foreach (PropertyInfo p in properties)
{
if (p.PropertyType == typeof(string))
{
p.SetValue(model, dr[colNames[i
++]], null);
}
else if (p.PropertyType == typeof(int))
{
p.SetValue(model,
int.Parse(dr[colNames[i++]].ToString()), null);
}
else if (p.PropertyType == typeof(bool))
{
p.SetValue(model,
bool.Parse(dr[colNames[i++]].ToString()), null);
}
else if (p.PropertyType == typeof(DateTime))
{
p.SetValue(model, DateTime.Parse(dr[colNames[i
++]].ToString()), null);
}
else if (p.PropertyType == typeof(float))
{
p.SetValue(model,
float.Parse(dr[colNames[i++]].ToString()), null);
}
else if (p.PropertyType == typeof(double))
{
p.SetValue(model,
double.Parse(dr[colNames[i++]].ToString()), null);
}
}

list.Add(model);
}

return list;
}


/// <summary>
/// 按照属性顺序的列名集合
/// </summary>
private IList<string> GetColumnNames(DataColumnCollection dcc)
{
PropertyInfo[] properties
= typeof(T).GetProperties();//获取实体类型的属性集合

//由于集合中的元素是确定的,所以可以指定元素的个数,系统就不会分配多余的空间,效率会高点
IList<string> ilist = new List<string>(dcc.Count);

foreach (PropertyInfo p in properties)
{
foreach (DataColumn dc in dcc)
{
if (dc.ColumnName.ToLower().Contains(p.Name.ToLower()))
{
ilist.Add(dc.ColumnName);
}
}
}

return ilist;
}

}
}
复制代码

目录
相关文章
|
10月前
|
数据库
dataTable转list
dataTable转list
64 0
DataTable to List<实体>
1.公共方法 1 #region dataConvert 2 /// 3 /// 从数据行返回数据实体对象 4 /// 5 /// 数据实体类型 6 /// 数据行 7 ...
672 0
|
JSON 数据格式
Json字符串转DataTable
/// /// 将json转换为DataTable /// /// 得到的json /// public static DataTable JsonToDT(string strJson) ...
1266 0
将dataGridView数据转成DataTable
如已绑定过数据源: DataTable dt = (dataGridView1.DataSource as DataTable) 如未绑定过数据源:public DataTable GetDgvToTable(DataGridView dgv)     ...
1404 0
|
JSON C# 数据格式
C# DataTable 转换成JSON数据
原文:C# DataTable 转换成JSON数据   using System; using System.Collections.Generic; using System.Data; using System.
1297 0