ModelsConvert.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text;
  8. namespace NXWMS.Client.Code.Converter
  9. {
  10. /// <summary>
  11. /// 模型转换
  12. /// </summary>
  13. public static class ModelsConvert
  14. {
  15. #region private
  16. /// <summary>
  17. /// 模型转换成Datatable
  18. /// </summary>
  19. /// <typeparam name="T"></typeparam>
  20. /// <param name="collection"></param>
  21. /// <returns></returns>
  22. public static DataTable ModelsToDataTable<T>(IEnumerable<T> collection)
  23. {
  24. var props = typeof(T).GetProperties();
  25. var dt = new DataTable();
  26. dt.Columns.AddRange(props.Where(m => !(m.PropertyType.IsGenericType) && (m.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))).
  27. Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
  28. if (collection.Count() > 0)
  29. {
  30. for (int i = 0; i < collection.Count(); i++)
  31. {
  32. ArrayList tempList = new ArrayList();
  33. foreach (PropertyInfo pi in props)
  34. {
  35. object obj = pi.GetValue(collection.ElementAt(i), null);
  36. tempList.Add(obj);
  37. }
  38. object[] array = tempList.ToArray();
  39. dt.LoadDataRow(array, true);
  40. }
  41. }
  42. return dt;
  43. }
  44. #endregion
  45. /// <summary>
  46. /// Convert a List{T} to a DataTable.
  47. /// </summary>
  48. public static DataTable ToDataTable<T>(IEnumerable<T> items)
  49. {
  50. var tb = new DataTable(typeof(T).Name);
  51. PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
  52. foreach (PropertyInfo prop in props)
  53. {
  54. Type t = GetCoreType(prop.PropertyType);
  55. tb.Columns.Add(prop.Name, t);
  56. }
  57. foreach (T item in items)
  58. {
  59. var values = new object[props.Length];
  60. for (int i = 0; i < props.Length; i++)
  61. {
  62. values[i] = props[i].GetValue(item, null);
  63. }
  64. tb.Rows.Add(values);
  65. }
  66. return tb;
  67. }
  68. /// <summary>
  69. /// Determine of specified type is nullable
  70. /// </summary>
  71. public static bool IsNullable(Type t)
  72. {
  73. return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
  74. }
  75. /// <summary>
  76. /// Return underlying type if type is Nullable otherwise return the type
  77. /// </summary>
  78. public static Type GetCoreType(Type t)
  79. {
  80. if (t != null && IsNullable(t))
  81. {
  82. if (!t.IsValueType)
  83. {
  84. return t;
  85. }
  86. else
  87. {
  88. return Nullable.GetUnderlyingType(t);
  89. }
  90. }
  91. else
  92. {
  93. return t;
  94. }
  95. }
  96. }
  97. }