其实早就该写的,哈哈,不过今天刚想起来注册,热热手,就写一下,哈哈。
直接上内容吧:
建立一个控制台应用程序,
List<students> Studentlist =
new List<students>{
new students{ Name = "zhagnsan1", Chinese = , Math = , English = },
new students{ Name = "zhagnsan2", Chinese = , Math = , English = },
new students{ Name = "zhagnsan3", Chinese = , Math = , English = }
};
DataTable dt = ListToDatatableHelper.ToDataTable(Studentlist);
this.dataGridView1.DataSource = dt; List<students> list = DatatableToListHelper.ConvertToList(dt); public class students
{
public string Name { get; set; }
public double English { get; set; }
public double Chinese { get; set; }
public double Math { get; set; }
}
ListToDatatableHelper.cs中的内容为:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace ListToDatatable
{
public class ListToDatatableHelper
{
/// <summary>
/// Convert a List{T} to a DataTable.
/// </summary>
public static DataTable ToDataTable<T>(List<T> items)
{
var tb = new DataTable(typeof(T).Name); PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
} foreach (T item in items)
{
var values = new object[props.Length]; for (int i = ; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
} tb.Rows.Add(values);
} return tb;
} /// <summary>
/// Determine of specified type is nullable
/// </summary>
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
} /// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
public static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
} //*************************************************
/// <summary>
/// List转Datatable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static IList<T> ConvertTo<T>(DataTable table)
{
if (table == null)
{
return null;
} List<DataRow> rows = new List<DataRow>(); foreach (DataRow row in table.Rows)
{
rows.Add(row);
} return ConvertTo<T>(rows);
} public static IList<T> ConvertTo<T>(IList<DataRow> rows)
{
IList<T> list = null; if (rows != null)
{
list = new List<T>(); foreach (DataRow row in rows)
{
T item = CreateItem<T>(row);
list.Add(item);
}
} return list;
} public static T CreateItem<T>(DataRow row)
{
T obj = default(T);
if (row != null)
{
obj = Activator.CreateInstance<T>(); foreach (DataColumn column in row.Table.Columns)
{
PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
try
{
object value = row[column.ColumnName];
prop.SetValue(obj, value, null);
}
catch
{ //You can log something here
//throw;
}
}
} return obj;
}
}
}
DatatableToListHelper.cs中的内容为:
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static ListToDatatable.Form1; namespace ListToDatatable
{
class DatatableToListHelper
{
/// <summary>
/// 利用反射和泛型
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static List<students> ConvertToList(DataTable dt)
{
// 定义集合
List<students> ts = new List<students>(); // 获得此模型的类型
Type type = typeof(students);
//定义一个临时变量
string tempName = string.Empty;
//遍历DataTable中所有的数据行
foreach (DataRow dr in dt.Rows)
{
students t = new students();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
//遍历该对象的所有属性
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;//将属性名称赋值给临时变量
//检查DataTable是否包含此列(列名==对象的属性名)
if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;//该属性不可写,直接跳出
//取值
object value = dr[tempName];
//如果非空,则赋给对象的属性
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
//对象添加到泛型集合中
ts.Add(t);
}
return ts;
}
}
}
OK,这是引用类型的list转datatable,完毕。