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


在将DataTable转换为List时,找到了网上的方案,原文链接: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 ToList(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;
    }
}