使用扩展方法将DataTable转换为List<T>
在将DataTable转换为List
使用时,遇到DbNull无法正常转换的问题,所以做了修正补充,继续发代码上来。
欢迎补充修正。
using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Reflection; public static class DataTableExtensions { public static IListToList (this DataTable table) where T : new() { IList properties = typeof(T).GetProperties().ToList(); IList result = new List (); foreach (var row in table.Rows) { var item = CreateItemFromRow ((DataRow)row, properties); result.Add(item); } return result; } public static IList ToList (this DataTable table, Dictionary<string, string> mappings) where T : new() { IList properties = typeof(T).GetProperties().ToList(); IList result = new List (); foreach (var row in table.Rows) { var item = CreateItemFromRow ((DataRow)row, properties, mappings); result.Add(item); } return result; } private static T CreateItemFromRow (DataRow row, IList 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 (DataRow row, IList 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; } }