You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.9 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Reflection;
  6. namespace Swift.DAL.Library
  7. {
  8. public static class Mapper
  9. {
  10. public static IList<T> DataTableToClass<T>(DataTable Table) where T : class, new()
  11. {
  12. var dataList = new List<T>(Table.Rows.Count);
  13. Type classType = typeof(T);
  14. IList<PropertyInfo> propertyList = classType.GetProperties();
  15. if (propertyList.Count == 0)
  16. return new List<T>();
  17. List<string> columnNames = Table.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToList();
  18. try
  19. {
  20. foreach (DataRow dataRow in Table.AsEnumerable().ToList())
  21. {
  22. var classObject = new T();
  23. foreach (PropertyInfo property in propertyList)
  24. {
  25. if (property != null && property.CanWrite)
  26. {
  27. if (columnNames.Contains(property.Name))
  28. {
  29. if (dataRow[property.Name] != System.DBNull.Value)
  30. {
  31. object propertyValue = System.Convert.ChangeType(
  32. dataRow[property.Name],
  33. property.PropertyType
  34. );
  35. property.SetValue(classObject, propertyValue, null);
  36. }
  37. }
  38. }
  39. }
  40. dataList.Add(classObject);
  41. }
  42. return dataList;
  43. }
  44. catch
  45. {
  46. return new List<T>();
  47. }
  48. }
  49. }
  50. }