Guest User

DataTable to List

a guest
Mar 27th, 2015
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.79 KB | None | 0 0
  1. public static List<T> Map<T>(DataTable data) where T : class, new()
  2.         {
  3.                 List<T> list = new List<T>();
  4.                 foreach (var row in data.AsEnumerable())
  5.                 {
  6.                     T obj = new T();
  7.                     foreach (DataColumn column in data.Columns)
  8.                     {
  9.                         var property = obj.GetType().GetProperty(column.ColumnName);
  10.                         if (property != null)
  11.                         {
  12.                             if (column.DataType == property.PropertyType)
  13.                                 property.SetValue(obj, row.Field<object>(column.ColumnName), null);
  14.                         }
  15.                     }
  16.                     list.Add(obj);
  17.                 }
  18.                 return list;
  19.         }
Advertisement
Add Comment
Please, Sign In to add comment