首页 > 其他 > 详细

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

时间:2016-12-29 19:16:12      阅读:197      评论:0      收藏:0      [点我收藏+]

 

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

 

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

原文:http://www.cnblogs.com/wind-/p/6233816.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!