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;
}
}
}