Datatable转List集合

方案一:
使用泛型和反射相关知识

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace APIUpLoadData
{
    public class ToolsHelper<T> where T : new()  // 此处一定要加上new()

    {
        public static IList<T> DataTableToModel(DataTable dt)
        {

            IList<T> list = new List<T>();// 定义集合
            Type type = typeof(T); // 获得此模型的类型
            string tempName = "";
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
                foreach (PropertyInfo pro in propertys)
                {
                    tempName = pro.Name;
                    if (dt.Columns.Contains(tempName))
                    {
                        if (!pro.CanWrite) continue;
                        object value = dr[tempName];
                        if (value != DBNull.Value)
                            pro.SetValue(t, value, null);
                    }
                }
                list.Add(t);
            }
            return list;
        }

    }
}

方案二:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace APIUpLoadData
{
    public class PlastiaBoxModel
    {
        public string cusName { get; set; }
        public string cusAge { get; set; }
        public string cusSex { get; set; }
    }
}

  public static List<PlastiaBoxModel> Tolist(DataTable dt)
        {
            List<PlastiaBoxModel> list = new List<PlastiaBoxModel>();
            PlastiaBoxModel box = new PlastiaBoxModel();
            foreach (DataRow dr in dt.Rows)
            {
                box.cusName = dr["cusName"].ToString();
                box.cusAge = dr["cusAge"].ToString();
                box.cusSex = dr["cusSex"].ToString();

                list.Add(box);
            }
            return list;

        }
	///调用方法
	//dt----datatable数据
    List<PlastiaBoxModel> list=Program.Tolist(dt);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值