标签:using etc bnu ppi from get lis 使用 tab
在将DataTable转换为List<T>时,找到了网上的方案,原文链接:http://stackoverflow.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; } }
标签:using etc bnu ppi from get lis 使用 tab
原文地址:http://www.cnblogs.com/wind-/p/6233816.html