C# Model实体类 转换 DataTable,List<>集合 转换 DataTable
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Reflection;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
User user = new User();
user.UserName = "用户名";
user.Password = "密码";
user.Age = 20;
List<User> users = new List<User>();
for (int i = 0; i < 5; ++i)
{
user = new User();
user.UserName = "用户名" + i.ToString();
user.Password = "密码" + i.ToString();
user.Age = 20;
users.Add(user);
}
// Model -> DataTable
DataTable dt1 = ModelToDataTable<User>(user);
// List<> -> DataTable
DataTable dt2 = ListToDataTable<User>(users);
}
/// <summary>
/// Model -> DataTable
/// </summary>
/// <typeparam name="T">数据项</typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static DataTable ModelToDataTable<T>(T data)
{
try
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable dt = new DataTable();
// 创建栏
for (int i = 0; i < properties.Count; i++)
{
PropertyDescriptor property = properties[i];
dt.Columns.Add(property.Name, property.PropertyType);
}
object[] values = new object[properties.Count];
// 赋值
for (int i = 0; i < values.Length; i++)
{
values[i] = properties[i].GetValue(data);
}
dt.Rows.Add(values);
return dt;
}
catch
{
throw;
}
}
/// <summary>
/// List -> DataTable
/// </summary>
/// <typeparam name="T">数据项</typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ListToDataTable<T>(IList<T> list)
{
try
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable dt = new DataTable();
// 创建栏
for (int i = 0; i < properties.Count; i++)
{
PropertyDescriptor property = properties[i];
dt.Columns.Add(property.Name, property.PropertyType);
}
object[] values = new object[properties.Count];
// 赋值
foreach (T item in list)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = properties[i].GetValue(item);
}
dt.Rows.Add(values);
}
return dt;
}
catch
{
throw;
}
}
}
/// <summary>
/// 用户
/// </summary>
public class User
{
/// <summary>
/// 用户名
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 密码
/// </summary>
public string Password { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
}
}