DataTable轉換成IList(二)

來源:互聯網
上載者:User

作者:陳太漢

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

}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.