This article is a mirror article of machine translation, please click here to jump to the original article.

View: 22953|Reply: 0

[Source] .net converts DataTable into a collection

[Copy link]
Posted on 1/19/2016 12:22:57 PM | | |
  1. /// <summary>
  2.         /// 将DataTable转成集合
  3.         /// </summary>
  4.         /// <typeparam name="T"></typeparam>
  5.         /// <param name="dt"></param>
  6.         /// <returns></returns>
  7.         public static List<T> ToListFromDataTable<T>(this DataTable dt)
  8.         {
  9.             try
  10.             {
  11.                 List<T> list = new List<T>();
  12.                 T t = default(T);
  13.                 PropertyInfo[] propertypes = null;
  14.                 string tempName = string.Empty;

  15.                 foreach (DataRow row in dt.Rows)
  16.                 {
  17.                     t = Activator.CreateInstance<T>();
  18.                     propertypes = t.GetType().GetProperties();

  19.                     foreach (PropertyInfo pro in propertypes)
  20.                     {
  21.                         tempName = pro.Name;
  22.                         if (dt.Columns.Contains(tempName))
  23.                         {
  24.                             object value = row[tempName];
  25.                             if (value.GetType() == typeof(System.DBNull))
  26.                             {
  27.                                 value = null;
  28.                             }
  29.                             pro.SetValue(t, value, null);
  30.                         }
  31.                     }
  32.                     list.Add(t);
  33.                 }
  34.                 return list;
  35.             }
  36.             catch
  37.             {
  38.                 return null;
  39.             }
  40.         }
Copy code






Previous:SQL Server types correspond to C# types
Next:The extension is not listed in the Chrome Web Store and may have been added without your knowledge.
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com