DataTable 和List 相互转换

http://apps.hi.baidu.com/share/detail/5752088

 

文本Tag: ASP.NET 微软 .NET web开发

【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表达式来提高效率..

 

----------------------------------------

  1. publicclass CollectionHelper   
  2. {   
  3.     private CollectionHelper()   
  4.      {   
  5.      }   
  6.   
  7.     publicstatic DataTable ConvertTo<T>(IList<T> list)   
  8.      {   
  9.          DataTable table = CreateTable<T>();   
  10.          Type entityType = typeof(T);   
  11.          PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);   
  12.   
  13.         foreach (T item in list)   
  14.          {   
  15.              DataRow row = table.NewRow();   
  16.   
  17.             foreach (PropertyDescriptor prop in properties)   
  18.              {   
  19.                  row[prop.Name] = prop.GetValue(item);   
  20.              }   
  21.   
  22.              table.Rows.Add(row);   
  23.          }   
  24.   
  25.         return table;   
  26.      }   
  27.   
  28.     publicstatic IList<T> ConvertTo<T>(IList<DataRow> rows)   
  29.      {   
  30.          IList<T> list = null;   
  31.   
  32.         if (rows != null)   
  33.          {   
  34.              list = new List<T>();   
  35.   
  36.             foreach (DataRow row in rows)   
  37.              {   
  38.                  T item = CreateItem<T>(row);   
  39.                  list.Add(item);   
  40.              }   
  41.          }   
  42.   
  43.         return list;   
  44.      }   
  45.   
  46.     publicstatic IList<T> ConvertTo<T>(DataTable table)   
  47.      {   
  48.         if (table == null)   
  49.          {   
  50.             returnnull;   
  51.          }   
  52.   
  53.          List<DataRow> rows = new List<DataRow>();   
  54.   
  55.         foreach (DataRow row in table.Rows)   
  56.          {   
  57.              rows.Add(row);   
  58.          }   
  59.   
  60.         return ConvertTo<T>(rows);   
  61.      }   
  62.   
  63.     publicstatic T CreateItem<T>(DataRow row)   
  64.      {   
  65.          T obj = default(T);   
  66.         if (row != null)   
  67.          {   
  68.              obj = Activator.CreateInstance<T>();   
  69.   
  70.             foreach (DataColumn column in row.Table.Columns)   
  71.              {   
  72.                  PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);   
  73.                 try  
  74.                  {   
  75.                     object value = row[column.ColumnName];   
  76.                      prop.SetValue(obj, value, null);   
  77.                  }   
  78.                 catch  
  79.                  {   
  80.                     // You can log something here   
  81.                     throw;   
  82.                  }   
  83.              }   
  84.          }   
  85.   
  86.         return obj;   
  87.      }   
  88.   
  89.     publicstatic DataTable CreateTable<T>()   
  90.      {   
  91.          Type entityType = typeof(T);   
  92.          DataTable table = new DataTable(entityType.Name);   
  93.          PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);   
  94.   
  95.         foreach (PropertyDescriptor prop in properties)   
  96.          {   
  97.              table.Columns.Add(prop.Name, prop.PropertyType);   
  98.          }   
  99.   
  100.         return table;   
  101.      }   
  102. }   
  103.   
  104.   
  105. To see the full code in action, check this sample out:   
  106.   
  107. publicclass MyClass   
  108. {   
  109.     publicstaticvoid Main()   
  110.      {   
  111.          List<Customer> customers = new List<Customer>();   
  112.   
  113.         for (int i = 0; i < 10; i++)   
  114.          {   
  115.              Customer c = new Customer();   
  116.              c.Id = i;   
  117.              c.Name = "Customer " + i.ToString();   
  118.   
  119.              customers.Add(c);   
  120.          }   
  121.   
  122.          DataTable table = CollectionHelper.ConvertTo<Customer>(customers);   
  123.   
  124.         foreach (DataRow row in table.Rows)   
  125.          {   
  126.              Console.WriteLine("Customer");   
  127.              Console.WriteLine("---------------");   
  128.   
  129.             foreach (DataColumn column in table.Columns)   
  130.              {   
  131.                 object value = row[column.ColumnName];   
  132.                  Console.WriteLine("{0}: {1}", column.ColumnName, value);   
  133.              }   
  134.   
  135.              Console.WriteLine();   
  136.          }   
  137.   
  138.          RL();   
  139.      }
  140.      #region Helper methods   
  141.   
  142.     privatestaticvoid WL(object text, paramsobject[] args)   
  143.      {   
  144.          Console.WriteLine(text.ToString(), args);   
  145.      }   
  146.   
  147.     privatestaticvoid RL()   
  148.      {   
  149.          Console.ReadLine();   
  150.      }   
  151.   
  152.     privatestaticvoid Break()   
  153.      {   
  154.          System.Diagnostics.Debugger.Break();   
  155.      }
  156.      #endregion   
  157. }  

你可能感兴趣的:(Datatable)