DataTable转IEnumerable

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_32157579/article/details/101627841
using System.Collections.Generic;

namespace System.Data
{
    public static class DataTableExtend
    {
        /// <summary>
        /// DataTable转换成IEnumerable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        public static IEnumerable<T> ToEnumerable<T>(this DataTable dataTable) where T : class, new()
        {
            return dataTable.AsEnumerable().Select(s => s.ToModel<T>());
        }

        /// <summary>
        /// DataRow转换成Model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataRow"></param>
        /// <returns></returns>
        public static T ToModel<T>(this DataRow dataRow) where T : class, new()
        {
            T model = new T();
            foreach (var property in model.GetType().GetProperties())
            {
                foreach (DataColumn key in dataRow.Table.Columns)
                {
                    string columnName = key.ColumnName;
                    if (!string.IsNullOrEmpty(dataRow[columnName].ToString()))
                    {
                        string propertyNameToMatch = columnName;
                        if (property.Name.ToLower() == propertyNameToMatch.ToLower())
                        {
                            Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                            object safeValue = (dataRow[columnName] == null) ? null : Convert.ChangeType(dataRow[columnName], t);
                            property.SetValue(model, safeValue, null);
                        }
                    }
                }
            }
            return model;
        }
    }
}

测试

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace Test
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    public class Program
    {
        static void Main(string[] args)
        {
            DataTable table = new DataTable();
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Age", typeof(int));
            for (int i = 0; i < 5; i++)
            {
                table.Rows.Add("Test" + i, i);
            }
            List<Person> list = table.ToEnumerable<Person>().ToList();
            foreach (Person person in list)
            {
                Console.WriteLine(person.Name+","+person.Age);
            }
        }
    }
}

结果
image.png

猜你喜欢

转载自blog.csdn.net/qq_32157579/article/details/101627841
今日推荐