C#将datatable数据批量放入类对象列中

有时候需要从数据表中的数据批量生成类列表。
本文应用了反射获取属性,属性类型
以及自定义特性,
扩展方法(扩展方法需要在顶级静态类中定义)
等相关方法

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp4
{

    public static class mytest
    {
        public static T CellToT<T>(this object DataTableCell)
        {
            try
            {
                T t = default;
                string str = DataTableCell == DBNull.Value ? "" : DataTableCell.ToString();
                t = (T)Convert.ChangeType(str, typeof(T));
                return t;
            }
            catch (Exception)
            { return default; }
        }
        public static object ConvertTo(this string str,Type objType)
        {
            return Convert.ChangeType(str, objType);
        }
        public class TestClass
        {

            public string StringCol { get; set; }
            public bool BoolCol { get; set; }
            [DT("IntCol")]
            public int MyInt { get; set; }
        }
        public class DTAttribute : Attribute
        {
            public DTAttribute()
            { }
            public DTAttribute(string colname)
            {
                ColName = colname;
            }
            public string ColName { get; set; }
        }
        public static List<T> ToList<T>(this DataTable dataTable, bool IsCareCase = true) where T : class, new()
        {
            try
            {
                if (dataTable == null) return null;
                List<T> TList = new List<T>();

                foreach (DataRow row in dataTable.Rows)
                {
                    var props = typeof(T).GetProperties();
                    T t = Activator.CreateInstance<T>();
                    foreach (DataColumn col in dataTable.Columns)
                    {
                        foreach (var p in props)
                        {
                            if (!p.CanWrite) continue;
                            var colName = p.Name;
                            var arrs = p.GetCustomAttributes(typeof(DTAttribute), false);
                            if (arrs != null && arrs.Count() > 0)
                            {
                                colName = ((DTAttribute)arrs[0]).ColName;
                            }
                            bool b = IsCareCase ? colName == col.ColumnName : colName.ToLower() == col.ColumnName.ToLower();
                            if (b)
                            {
                                var mmtype = p.PropertyType;
                                var str = row[col.ColumnName].CellToT<string>();
                                if (str != "")
                                {
                                    var v1 = str.ConvertTo(p.PropertyType);
                                    p.SetValue(t, v1);
                                }
                            }
                        }
                    }
                    TList.Add(t);
                }
                return TList;
            }catch(Exception)
            {
                return new List<T>();
            }
        }
        public static void DoWork(DataTable dt)
        {
            var testclass = dt.ToList<TestClass>();

        }

    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DataTable dt = new DataTable();
        private void button1_Click(object sender, EventArgs e)
        {
            dt.Clear();
                // 列强制转换
            for (int count = 0; count < dgv.Columns.Count; count++)
                {
                    DataColumn dc = new DataColumn(dgv.Columns[count].Name.ToString());
                    dt.Columns.Add(dc);
                }

                // 循环行
                for (int count = 0; count < dgv.Rows.Count; count++)
                {
                    DataRow dr = dt.NewRow();
                    for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
                    {
                        dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value);
                    }
                    dt.Rows.Add(dr);
                }
            MessageBox.Show("导出成功!");
            mytest.DoWork(dt);
        }
       

       

        
     
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值