Guest User

Untitled

a guest
Jun 22nd, 2018
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.13 KB | None | 0 0
  1. public static class DataTableExtensions
  2. {
  3.     private static Dictionary<Type,IList<PropertyInfo>> typeDictionary = new Dictionary<Type, IList<PropertyInfo>>();
  4.     public static IList<PropertyInfo> GetPropertiesForType<T>()
  5.     {
  6.         var type = typeof(T);
  7.         if(!typeDictionary.ContainsKey(typeof(T))
  8.         {
  9.             typeDictionary.Add(type, type.GetProperties().ToList());
  10.         }
  11.         return typeDictionary[type];
  12.     }
  13.  
  14.     public static IList<T> ToList<T>(this DataTable table) where T : new()
  15.     {
  16.         IList<PropertyInfo> properties = GetPropertiesForType<T>();
  17.         IList<T> result = new List<T>();
  18.  
  19.         foreach (var row in table.Rows)
  20.         {
  21.             var item = CreateItemFromRow<T>((DataRow)row, properties);
  22.             result.Add(item);
  23.         }
  24.  
  25.         return result;
  26.     }
  27.  
  28.     private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
  29.     {
  30.         T item = new T();
  31.         foreach (var property in properties)
  32.         {
  33.             property.SetValue(item, row[property.Name], null);
  34.         }
  35.         return item;
  36.     }
  37.  
  38. }
Add Comment
Please, Sign In to add comment