DataTable 和List 相互转换
http://apps.hi.baidu.com/share/detail/5752088
【IT168技术文档】 扩展方法(1) DataTable 和List 相互转换
DataTable 转换为List<T> 的我们可以通过扩展DataTable来简化
public static class DataTableExtensions
{
/// <summary>
/// DataTable 转换为List 集合
/// </summary>
/// <typeparam name="TResult">类型</typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static List<TResult> ToList<TResult>(this DataTable dt) where TResult : class,new()
{
//创建一个属性的列表
List<PropertyInfo> prlist = new List<PropertyInfo>();
//获取TResult的类型实例 反射的入口
Type t = typeof(TResult);
//获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表
Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
//创建返回的集合
List<TResult> oblist = new List<TResult>();
foreach (DataRow row in dt.Rows)
{
//创建TResult的实例
TResult ob = new TResult();
//找到对应的数据 并赋值
prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
//放入到返回的集合中.
oblist.Add(ob);
}
return oblist;
}
}
相反 的也需要List<T> 转换为DataTable 我们可以通过扩展IEnumberable<T> 来实现
/// <summary>/// 转换为一个DataTable
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
public static DataTable ToDataTable<TResult>(this IEnumerable<TResult> value) where TResult : class
{
//创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口
Type type = typeof(TResult);
DataTable dt = new DataTable();
//把所有的public属性加入到集合 并添加DataTable的列
Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p);dt.Columns.Add(p.Name, p.PropertyType); });
foreach (var item in value)
{
//创建一个DataRow实例
DataRow row = dt.NewRow();
//给row 赋值
pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
//加入到DataTable
dt.Rows.Add(row);
}
return dt;
}
}
可以通过上面的代码看出 都是主要通过反射 来实现的. 反射的效率似有点慢. 但是可以接受..
当然你也可以通过表达式树 动态的构造Lambda表达式来提高效率..
----------------------------------------
- publicclass CollectionHelper
- {
- private CollectionHelper()
- {
- }
- publicstatic DataTable ConvertTo<T>(IList<T> list)
- {
- DataTable table = CreateTable<T>();
- Type entityType = typeof(T);
- PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
- foreach (T item in list)
- {
- DataRow row = table.NewRow();
- foreach (PropertyDescriptor prop in properties)
- {
- row[prop.Name] = prop.GetValue(item);
- }
- table.Rows.Add(row);
- }
- return table;
- }
- publicstatic 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;
- }
- publicstatic IList<T> ConvertTo<T>(DataTable table)
- {
- if (table == null)
- {
- returnnull;
- }
- List<DataRow> rows = new List<DataRow>();
- foreach (DataRow row in table.Rows)
- {
- rows.Add(row);
- }
- return ConvertTo<T>(rows);
- }
- publicstatic 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;
- }
- publicstatic DataTable CreateTable<T>()
- {
- Type entityType = typeof(T);
- DataTable table = new DataTable(entityType.Name);
- PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
- foreach (PropertyDescriptor prop in properties)
- {
- table.Columns.Add(prop.Name, prop.PropertyType);
- }
- return table;
- }
- }
- To see the full code in action, check this sample out:
- publicclass MyClass
- {
- publicstaticvoid Main()
- {
- List<Customer> customers = new List<Customer>();
- for (int i = 0; i < 10; i++)
- {
- Customer c = new Customer();
- c.Id = i;
- c.Name = "Customer " + i.ToString();
- customers.Add(c);
- }
- DataTable table = CollectionHelper.ConvertTo<Customer>(customers);
- foreach (DataRow row in table.Rows)
- {
- Console.WriteLine("Customer");
- Console.WriteLine("---------------");
- foreach (DataColumn column in table.Columns)
- {
- object value = row[column.ColumnName];
- Console.WriteLine("{0}: {1}", column.ColumnName, value);
- }
- Console.WriteLine();
- }
- RL();
- }
- #region Helper methods
- privatestaticvoid WL(object text, paramsobject[] args)
- {
- Console.WriteLine(text.ToString(), args);
- }
- privatestaticvoid RL()
- {
- Console.ReadLine();
- }
- privatestaticvoid Break()
- {
- System.Diagnostics.Debugger.Break();
- }
- #endregion
- }
posted on 2012-06-12 09:23 HOT SUMMER 阅读(403) 评论(0) 编辑 收藏 举报