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