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.

323 lines
12 KiB

2 years ago
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Text;
  9. namespace EasyBL
  10. {
  11. public static class ComTool
  12. {
  13. /// <summary>
  14. /// Converts DataTable To List
  15. /// </summary>
  16. /// <typeparam name="TSource"></typeparam>
  17. /// <param name="dataTable"></param>
  18. /// <returns></returns>
  19. public static List<TSource> ToList_1<TSource>(this DataTable dataTable) where TSource : new()
  20. {
  21. var dataList = new List<TSource>();
  22. const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;
  23. var objFieldNames = (from PropertyInfo aProp in typeof(TSource).GetProperties(flags)
  24. select new
  25. {
  26. aProp.Name,
  27. Type = Nullable.GetUnderlyingType(aProp.PropertyType) ??
  28. aProp.PropertyType
  29. }).ToList();
  30. var dataTblFieldNames = (from DataColumn aHeader in dataTable.Columns
  31. select new
  32. {
  33. Name = aHeader.ColumnName,
  34. Type = aHeader.DataType
  35. }).ToList();
  36. var commonFields = objFieldNames.Intersect(dataTblFieldNames).ToList();
  37. foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
  38. {
  39. var aTSource = new TSource();
  40. foreach (var aField in commonFields)
  41. {
  42. var propertyInfos = aTSource.GetType().GetProperty(aField.Name);
  43. var value = (dataRow[aField.Name] == DBNull.Value) ?
  44. null : dataRow[aField.Name]; //if database field is nullable
  45. propertyInfos.SetValue(aTSource, value, null);
  46. }
  47. dataList.Add(aTSource);
  48. }
  49. return dataList;
  50. }
  51. /// <summary>
  52. /// 將自動轉table。
  53. /// 通常會搭配
  54. /// </summary>
  55. /// <typeparam name="T"></typeparam>
  56. /// <param name="data"></param>
  57. /// <param name="tableName"></param>
  58. /// <returns></returns>
  59. public static DataTable ListToDataTable<T>(this IList<T> data, string tableName = "tb")
  60. {
  61. var table = new DataTable(tableName);
  62. //special handling for value types and string
  63. if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
  64. {
  65. var dc = new DataColumn("Value");
  66. table.Columns.Add(dc);
  67. foreach (T item in data)
  68. {
  69. var dr = table.NewRow();
  70. dr[0] = item;
  71. table.Rows.Add(dr);
  72. }
  73. }
  74. else
  75. {
  76. var properties = TypeDescriptor.GetProperties(typeof(T));
  77. foreach (PropertyDescriptor prop in properties)
  78. {
  79. table.Columns.Add(prop.Name,
  80. Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
  81. }
  82. foreach (T item in data)
  83. {
  84. var row = table.NewRow();
  85. foreach (PropertyDescriptor prop in properties)
  86. {
  87. try
  88. {
  89. row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
  90. }
  91. catch (Exception)
  92. {
  93. row[prop.Name] = DBNull.Value;
  94. }
  95. }
  96. table.Rows.Add(row);
  97. }
  98. }
  99. return table;
  100. }
  101. /// <summary>
  102. /// <param name="list">todo: describe list parameter on ToDataTable</param><param
  103. /// name="list">todo: describe list parameter on ToDataTable</param> 转化一个DataTable
  104. /// </summary>
  105. /// <param name="list">todo: describe list parameter on ToDataTable</param>
  106. /// <typeparam name="T"></typeparam>
  107. /// <param name="list"></param>
  108. /// <returns></returns>
  109. public static DataTable ToDataTable<T>(this IEnumerable<T> list)
  110. {
  111. //创建属性的集合
  112. var pList = new List<PropertyInfo>();
  113. //获得反射的入口
  114. var type = typeof(T);
  115. var dt = new DataTable();
  116. //把所有的public属性加入到集合 并添加DataTable的列
  117. Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
  118. foreach (var item in list)
  119. {
  120. //创建一个DataRow实例
  121. var row = dt.NewRow();
  122. //给row 赋值
  123. pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
  124. //加入到DataTable
  125. dt.Rows.Add(row);
  126. }
  127. return dt;
  128. }
  129. /// <summary>
  130. /// DataTable 转换为List 集合
  131. /// </summary>
  132. /// <typeparam name="TResult">类型</typeparam>
  133. /// <param name="dt">DataTable</param>
  134. /// <returns></returns>
  135. public static List<T> ToList<T>(this DataTable dt) where T : class, new()
  136. {
  137. //创建一个属性的列表
  138. var prlist = new List<PropertyInfo>();
  139. //获取TResult的类型实例 反射的入口
  140. var t = typeof(T);
  141. //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表
  142. Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
  143. //创建返回的集合
  144. var oblist = new List<T>();
  145. foreach (DataRow row in dt.Rows)
  146. {
  147. //创建TResult的实例
  148. var ob = new T();
  149. //找到对应的数据 并赋值
  150. prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
  151. //放入到返回的集合中.
  152. oblist.Add(ob);
  153. }
  154. return oblist;
  155. }
  156. /// <summary>
  157. /// 将集合类转换成DataTable
  158. /// </summary>
  159. /// <param name="list">集合</param>
  160. /// <returns></returns>
  161. public static DataTable ToDataTableTow(IList list)
  162. {
  163. var result = new DataTable();
  164. if (list.Count > 0)
  165. {
  166. var propertys = list[0].GetType().GetProperties();
  167. foreach (PropertyInfo pi in propertys)
  168. {
  169. result.Columns.Add(pi.Name, pi.PropertyType);
  170. }
  171. for (int i = 0; i < list.Count; i++)
  172. {
  173. var tempList = new ArrayList();
  174. foreach (PropertyInfo pi in propertys)
  175. {
  176. var obj = pi.GetValue(list[i], null);
  177. tempList.Add(obj);
  178. }
  179. var array = tempList.ToArray();
  180. result.LoadDataRow(array, true);
  181. }
  182. }
  183. return result;
  184. }
  185. /// <summary>
  186. /// 将集合类转换成DataTable
  187. /// </summary>
  188. /// <param name="list">集合</param>
  189. /// <returns></returns>
  190. public static DataTable DicToDataTable(List<Dictionary<string, object>> list)
  191. {
  192. var result = new DataTable("tb");
  193. if (list.Count > 0)
  194. {
  195. var dic = list[0];
  196. foreach (string key in dic.Keys)
  197. {
  198. result.Columns.Add(key);
  199. }
  200. foreach (Dictionary<string, object> info in list)
  201. {
  202. var tempList = new ArrayList();
  203. foreach (string key in info.Keys)
  204. {
  205. tempList.Add(info[key]);
  206. }
  207. var array = tempList.ToArray();
  208. result.LoadDataRow(array, true);
  209. }
  210. }
  211. return result;
  212. }
  213. /// <summary>
  214. /// 将泛型集合类转换成DataTable <param name="list">todo: describe list parameter on
  215. /// ToDataTable</param><param name="list">todo: describe list parameter on ToDataTable</param>
  216. /// </summary>
  217. /// <typeparam name="T">集合项类型</typeparam>
  218. /// <param name="list">集合</param>
  219. /// <returns>数据集(表)</returns>
  220. public static DataTable ToDataTable<T>(IList<T> list)
  221. {
  222. return ToDataTable<T>(list, null);
  223. }
  224. /// <summary>
  225. /// 将泛型集合类转换成DataTable
  226. /// </summary>
  227. /// <typeparam name="T">集合项类型</typeparam>
  228. /// <param name="list">集合</param>
  229. /// <param name="propertyName">需要返回的列的列名</param>
  230. /// <returns>数据集(表)</returns>
  231. public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
  232. {
  233. var propertyNameList = new List<string>();
  234. if (propertyName != null)
  235. propertyNameList.AddRange(propertyName);
  236. var result = new DataTable();
  237. if (list.Count > 0)
  238. {
  239. var propertys = list[0].GetType().GetProperties();
  240. foreach (PropertyInfo pi in propertys)
  241. {
  242. if (propertyNameList.Count == 0)
  243. {
  244. result.Columns.Add(pi.Name, pi.PropertyType);
  245. }
  246. else
  247. {
  248. if (propertyNameList.Contains(pi.Name))
  249. result.Columns.Add(pi.Name, pi.PropertyType);
  250. }
  251. }
  252. for (int i = 0; i < list.Count; i++)
  253. {
  254. var tempList = new ArrayList();
  255. foreach (PropertyInfo pi in propertys)
  256. {
  257. if (propertyNameList.Count == 0)
  258. {
  259. var obj = pi.GetValue(list[i], null);
  260. tempList.Add(obj);
  261. }
  262. else
  263. {
  264. if (propertyNameList.Contains(pi.Name))
  265. {
  266. var obj = pi.GetValue(list[i], null);
  267. tempList.Add(obj);
  268. }
  269. }
  270. }
  271. var array = tempList.ToArray();
  272. result.LoadDataRow(array, true);
  273. }
  274. }
  275. return result;
  276. }
  277. public static string PadLeftEx(string str, int totalByteCount, char c)
  278. {
  279. var coding = Encoding.GetEncoding("gb2312");
  280. var dcount = 0;
  281. foreach (char ch in str.ToCharArray())
  282. {
  283. if (coding.GetByteCount(ch.ToString()) == 2)
  284. dcount++;
  285. }
  286. var w = str.PadRight(totalByteCount - dcount, c);
  287. return w;
  288. }
  289. public static string PadRightEx(string str, int totalByteCount, char c)
  290. {
  291. var coding = Encoding.GetEncoding("gb2312");
  292. var dcount = 0;
  293. foreach (char ch in str.ToCharArray())
  294. {
  295. if (coding.GetByteCount(ch.ToString()) == 2)
  296. dcount++;
  297. }
  298. var w = str.PadRight(totalByteCount - dcount, c);
  299. return w;
  300. }
  301. }
  302. }