DataTable转List

发布时间 2023-05-26 14:49:56作者: 哎嘿_zx
using System;
using System.Collections.Generic;
using System.Data;

/// <summary>
/// Class1 的摘要说明
/// </summary>
public class ConvertTool
{
    public static List<T> DataConvert<T>(DataTable tb)
    {
        List<T> lst = new List<T>();
        DataConvert<T>(tb, ref lst);
        return lst;
    }

    public static List<T> DataConvert<T>(DataTable tb, ref List<T> lst)
    {
        for (int i = 0; i < tb.Rows.Count; i++)
        {
            lst.Add(DataConvert<T>(tb.Rows[i]));
        }
        return lst;
    }

    public static T DataConvert<T>(DataRow row)
    {            //泛型 根据传来的类型创建实例对象
        var type = typeof(T);
        object obj = type.Assembly.CreateInstance(type.FullName);
        var c = (T)obj;
        DataConvert(row, ref c);
        return c;
    }

    //获取一个类对象的所有公共属性 遍历所有属性 并赋值
    public static T DataConvert<T>(DataRow row, ref T t)
    {
        var ps = t.GetType().GetProperties();
        var tbColumns = row.Table.Columns;
        foreach (var c in ps)
        {
            var colName = c.Name;
            if (tbColumns.Contains(colName))
            {
                object nr = row[colName] == DBNull.Value ? null : row[colName];
                if (nr == null)
                {
                    c.SetValue(t, nr, null);
                }
                else
                {
                    var nrType = c.PropertyType;
                    if (nrType == typeof(decimal) || nrType == typeof(decimal?))
                    {
                        nr = Convert.ToDecimal(nr);
                    }
                    else if (nrType == typeof(Int64) || nrType == typeof(Int64?))
                    {
                        nr = Convert.ToInt64(nr);
                    }
                    else if (nrType == typeof(double) || nrType == typeof(double?))
                    {
                        nr = Convert.ToDouble(nr);
                    }
                    else if (nrType == typeof(Int32) || nrType == typeof(Int32?))
                    {
                        nr = Convert.ToInt32(nr);
                    }
                    else if (nrType == typeof(Int16) || nrType == typeof(Int16?))
                    {
                        nr = Convert.ToInt16(nr);
                    }
                    c.SetValue(t, nr, null);
                }
            }
        }
        return t;
    }
}