C# List和DataTable的相互轉換


1、List轉DataTable

 /// <summary>
 /// list to datatable
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="collection"></param>
 /// <returns></returns>
 public  DataTable  ListToDt<T>(IEnumerable<T> collection)
 {
     var props = typeof(T).GetProperties();
     var dt = new DataTable();
     dt.Columns.AddRange(props.Select(p => new 
     DataColumn(p.Name, p.PropertyType)).ToArray());
     if (collection.Count() > 0)
     {
         for (int i = 0; i < collection.Count(); i++)
         {
             ArrayList tempList = new ArrayList();
             foreach (PropertyInfo pi in props)
             {
                 object obj = pi.GetValue(collection.ElementAt(i), null);
                 tempList.Add(obj);
             }
             object[] array = tempList.ToArray();
             dt.LoadDataRow(array, true);
          }
      }
      return dt;
 }

2、DataTable轉List

public class DtToList<T> where T : new()  
{
     /// <summary>
     /// datatable to list
     /// </summary>
     /// <param name="dt"></param>
     /// <returns></returns>
     public static  List<T> ConvertToModel(DataTable dt)
     {

         List<T> ts = new List<T>();// 定義集合
         Type type = typeof(T); // 獲得此模型的類型
         string tempName = "";
         foreach (DataRow dr in dt.Rows)
         {
             T t = new T();
             PropertyInfo[] propertys = t.GetType().GetProperties();// 獲得此模型的公共屬性
             foreach (PropertyInfo pi in propertys)
             {
                 tempName = pi.Name;
                 if (dt.Columns.Contains(tempName))
                 {
                     if (!pi.CanWrite) continue;
                     object value = dr[tempName];
                     if (value != DBNull.Value)
                        pi.SetValue(t, value, null);
                 }
             }
             ts.Add(t);
         }
         return ts;
     }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM