使用扩展方法将DataTable转换为List

在将DataTable转换为List<T>时,找到了网上的方案,原文链接:http://*.com/questions/4593663/fetch-datarow-to-c-sharp-object

使用时,遇到DbNull无法正常转换的问题,所以做了修正补充,继续发代码上来。

欢迎补充修正。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Reflection; public static class DataTableExtensions
{
public static IList<T> ToList<T>(this DataTable table) where T : new()
{
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
IList<T> result = new List<T>(); foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties);
result.Add(item);
} return result;
} public static IList<T> ToList<T>(this DataTable table, Dictionary<string, string> mappings) where T : new()
{
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
IList<T> result = new List<T>(); foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties, mappings);
result.Add(item);
} return result;
} private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var property in properties)
{
property.SetValue(item, row[property.Name], null);
}
return item;
} private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties, Dictionary<string, string> mappings) where T : new()
{
T item = new T();
foreach (var property in properties)
{
if (mappings.ContainsKey(property.Name))
property.SetValue(item, (row[mappings[property.Name]] == DBNull.Value) ? null : row[mappings[property.Name]], null);
}
return item;
}
}
上一篇:Conexant声卡实现内录功能(win7)


下一篇:maven工程之pom模板(hadoop、hive、hbase)