DataTableHelper.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. using System.Threading.Tasks;
  9. namespace ProjectBase.Util
  10. {
  11. /// <summary>
  12. /// DataTable操作辅助类
  13. /// </summary>
  14. public class DataTableHelper
  15. {
  16. /// <summary>
  17. /// 给DataTable增加一个自增列
  18. /// 如果DataTable 存在 identityid 字段 则 直接返回DataTable 不做任何处理
  19. /// </summary>
  20. /// <param name="dt">DataTable</param>
  21. /// <returns>返回Datatable 增加字段 identityid </returns>
  22. public static DataTable AddIdentityColumn(DataTable dt)
  23. {
  24. if (!dt.Columns.Contains("identityid"))
  25. {
  26. dt.Columns.Add("identityid");
  27. for (int i = 0; i < dt.Rows.Count; i++)
  28. {
  29. dt.Rows[i]["identityid"] = (i + 1).ToString();
  30. }
  31. }
  32. return dt;
  33. }
  34. /// <summary>
  35. /// 检查DataTable 是否有数据行
  36. /// </summary>
  37. /// <param name="dt">DataTable</param>
  38. /// <returns></returns>
  39. public static bool IsHaveRows(DataTable dt)
  40. {
  41. if (dt != null && dt.Rows.Count > 0)
  42. return true;
  43. return false;
  44. }
  45. /// <summary>
  46. /// DataTable转换成实体列表
  47. /// </summary>
  48. /// <typeparam name="T">实体 T </typeparam>
  49. /// <param name="table">datatable</param>
  50. /// <returns></returns>
  51. public static IList<T> DataTableToList<T>(DataTable table)
  52. where T : class
  53. {
  54. if (!IsHaveRows(table))
  55. return new List<T>();
  56. IList<T> list = new List<T>();
  57. T model = default(T);
  58. foreach (DataRow dr in table.Rows)
  59. {
  60. model = Activator.CreateInstance<T>();
  61. foreach (DataColumn dc in dr.Table.Columns)
  62. {
  63. object drValue = dr[dc.ColumnName];
  64. PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName);
  65. if (pi != null && pi.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
  66. {
  67. pi.SetValue(model, drValue, null);
  68. }
  69. }
  70. list.Add(model);
  71. }
  72. return list;
  73. }
  74. /// <summary>
  75. /// 实体列表转换成DataTable
  76. /// </summary>
  77. /// <typeparam name="T">实体</typeparam>
  78. /// <param name="list"> 实体列表</param>
  79. /// <returns></returns>
  80. public static DataTable ListToDataTable<T>(IList<T> list)
  81. where T : class
  82. {
  83. if (list == null || list.Count <= 0)
  84. {
  85. return null;
  86. }
  87. DataTable dt = new DataTable(typeof(T).Name);
  88. DataColumn column;
  89. DataRow row;
  90. PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
  91. int length = myPropertyInfo.Length;
  92. bool createColumn = true;
  93. foreach (T t in list)
  94. {
  95. if (t == null)
  96. {
  97. continue;
  98. }
  99. row = dt.NewRow();
  100. for (int i = 0; i < length; i++)
  101. {
  102. PropertyInfo pi = myPropertyInfo[i];
  103. string name = pi.Name;
  104. if (createColumn)
  105. {
  106. column = new DataColumn(name, pi.PropertyType);
  107. dt.Columns.Add(column);
  108. }
  109. row[name] = pi.GetValue(t, null);
  110. }
  111. if (createColumn)
  112. {
  113. createColumn = false;
  114. }
  115. dt.Rows.Add(row);
  116. }
  117. return dt;
  118. }
  119. /// <summary>
  120. /// 将泛型集合类转换成DataTable
  121. /// </summary>
  122. /// <typeparam name="T">集合项类型</typeparam>
  123. /// <param name="list">集合</param>
  124. /// <returns>数据集(表)</returns>
  125. public static DataTable ToDataTable<T>(IList<T> list)
  126. {
  127. return ToDataTable<T>(list, null);
  128. }
  129. /// <summary>
  130. /// 将泛型集合类转换成DataTable
  131. /// </summary>
  132. /// <typeparam name="T">集合项类型</typeparam>
  133. /// <param name="list">集合</param>
  134. /// <param name="propertyName">需要返回的列的列名</param>
  135. /// <returns>数据集(表)</returns>
  136. public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
  137. {
  138. List<string> propertyNameList = new List<string>();
  139. if (propertyName != null)
  140. propertyNameList.AddRange(propertyName);
  141. DataTable result = new DataTable();
  142. if (list.Count > 0)
  143. {
  144. PropertyInfo[] propertys = list[0].GetType().GetProperties();
  145. foreach (PropertyInfo pi in propertys)
  146. {
  147. if (propertyNameList.Count == 0)
  148. {
  149. result.Columns.Add(pi.Name, pi.PropertyType);
  150. }
  151. else
  152. {
  153. if (propertyNameList.Contains(pi.Name))
  154. {
  155. result.Columns.Add(pi.Name, pi.PropertyType);
  156. }
  157. }
  158. }
  159. for (int i = 0; i < list.Count; i++)
  160. {
  161. ArrayList tempList = new ArrayList();
  162. foreach (PropertyInfo pi in propertys)
  163. {
  164. if (propertyNameList.Count == 0)
  165. {
  166. object obj = pi.GetValue(list[i], null);
  167. tempList.Add(obj);
  168. }
  169. else
  170. {
  171. if (propertyNameList.Contains(pi.Name))
  172. {
  173. object obj = pi.GetValue(list[i], null);
  174. tempList.Add(obj);
  175. }
  176. }
  177. }
  178. object[] array = tempList.ToArray();
  179. result.LoadDataRow(array, true);
  180. }
  181. }
  182. return result;
  183. }
  184. /// <summary>
  185. /// 根据nameList里面的字段创建一个表格,返回该表格的DataTable
  186. /// </summary>
  187. /// <param name="nameList">包含字段信息的列表</param>
  188. /// <returns>DataTable</returns>
  189. public static DataTable CreateTable(List<string> nameList)
  190. {
  191. if (nameList.Count <= 0)
  192. return null;
  193. DataTable myDataTable = new DataTable();
  194. myDataTable.TableName = "tableName";//增加一个默认的名字
  195. foreach (string columnName in nameList)
  196. {
  197. myDataTable.Columns.Add(columnName, typeof(string));
  198. }
  199. return myDataTable;
  200. }
  201. /// <summary>
  202. /// 通过字符列表创建表字段,字段格式可以是:
  203. /// 1) a,b,c,d,e
  204. /// 2) a|int,b|string,c|bool,d|decimal
  205. /// </summary>
  206. /// <param name="nameString"></param>
  207. /// <returns></returns>
  208. public static DataTable CreateTable(string nameString)
  209. {
  210. string[] nameArray = nameString.Split(new char[] { ',', ';' });
  211. List<string> nameList = new List<string>();
  212. DataTable dt = new DataTable();
  213. dt.TableName = "tableName";//增加一个默认的名字
  214. foreach (string item in nameArray)
  215. {
  216. if (!string.IsNullOrEmpty(item))
  217. {
  218. string[] subItems = item.Split('|');
  219. if (subItems.Length == 2)
  220. {
  221. dt.Columns.Add(subItems[0], ConvertType(subItems[1]));
  222. }
  223. else
  224. {
  225. dt.Columns.Add(subItems[0]);
  226. }
  227. }
  228. }
  229. return dt;
  230. }
  231. private static Type ConvertType(string typeName)
  232. {
  233. typeName = typeName.ToLower().Replace("system.", "");
  234. Type newType = typeof(string);
  235. switch (typeName)
  236. {
  237. case "boolean":
  238. case "bool":
  239. newType = typeof(bool);
  240. break;
  241. case "int16":
  242. case "short":
  243. newType = typeof(short);
  244. break;
  245. case "int32":
  246. case "int":
  247. newType = typeof(int);
  248. break;
  249. case "long":
  250. case "int64":
  251. newType = typeof(long);
  252. break;
  253. case "uint16":
  254. case "ushort":
  255. newType = typeof(ushort);
  256. break;
  257. case "uint32":
  258. case "uint":
  259. newType = typeof(uint);
  260. break;
  261. case "uint64":
  262. case "ulong":
  263. newType = typeof(ulong);
  264. break;
  265. case "single":
  266. case "float":
  267. newType = typeof(float);
  268. break;
  269. case "string":
  270. newType = typeof(string);
  271. break;
  272. case "guid":
  273. newType = typeof(Guid);
  274. break;
  275. case "decimal":
  276. newType = typeof(decimal);
  277. break;
  278. case "double":
  279. newType = typeof(double);
  280. break;
  281. case "datetime":
  282. newType = typeof(DateTime);
  283. break;
  284. case "byte":
  285. newType = typeof(byte);
  286. break;
  287. case "char":
  288. newType = typeof(char);
  289. break;
  290. }
  291. return newType;
  292. }
  293. /// <summary>
  294. /// 获得从DataRowCollection转换成的DataRow数组
  295. /// </summary>
  296. /// <param name="drc">DataRowCollection</param>
  297. /// <returns></returns>
  298. public static DataRow[] GetDataRowArray(DataRowCollection drc)
  299. {
  300. int count = drc.Count;
  301. DataRow[] drs = new DataRow[count];
  302. for (int i = 0; i < count; i++)
  303. {
  304. drs[i] = drc[i];
  305. }
  306. return drs;
  307. }
  308. /// <summary>
  309. /// 将DataRow数组转换成DataTable,注意行数组的每个元素须具有相同的数据结构,
  310. /// 否则当有元素长度大于第一个元素时,抛出异常
  311. /// </summary>
  312. /// <param name="rows">行数组</param>
  313. /// <returns></returns>
  314. public static DataTable GetTableFromRows(DataRow[] rows)
  315. {
  316. if (rows.Length <= 0)
  317. {
  318. return new DataTable();
  319. }
  320. DataTable dt = rows[0].Table.Clone();
  321. dt.DefaultView.Sort = rows[0].Table.DefaultView.Sort;
  322. for (int i = 0; i < rows.Length; i++)
  323. {
  324. dt.LoadDataRow(rows[i].ItemArray, true);
  325. }
  326. return dt;
  327. }
  328. /// <summary>
  329. /// 排序表的视图
  330. /// </summary>
  331. /// <param name="dt"></param>
  332. /// <param name="sorts"></param>
  333. /// <returns></returns>
  334. public static DataTable SortedTable(DataTable dt, params string[] sorts)
  335. {
  336. if (dt.Rows.Count > 0)
  337. {
  338. string tmp = "";
  339. for (int i = 0; i < sorts.Length; i++)
  340. {
  341. tmp += sorts[i] + ",";
  342. }
  343. dt.DefaultView.Sort = tmp.TrimEnd(',');
  344. }
  345. return dt;
  346. }
  347. /// <summary>
  348. /// 根据条件过滤表的内容
  349. /// </summary>
  350. /// <param name="dt"></param>
  351. /// <param name="condition"></param>
  352. /// <returns></returns>
  353. public static DataTable FilterDataTable(DataTable dt, string condition)
  354. {
  355. if (condition.Trim() == "")
  356. {
  357. return dt;
  358. }
  359. else
  360. {
  361. DataTable newdt = new DataTable();
  362. newdt = dt.Clone();
  363. DataRow[] dr = dt.Select(condition);
  364. for (int i = 0; i < dr.Length; i++)
  365. {
  366. newdt.ImportRow((DataRow)dr[i]);
  367. }
  368. return newdt;
  369. }
  370. }
  371. /// <summary>
  372. /// 转换.NET的Type到数据库参数的类型
  373. /// </summary>
  374. /// <param name="t"></param>
  375. /// <returns></returns>
  376. public static DbType TypeToDbType(Type t)
  377. {
  378. DbType dbt;
  379. try
  380. {
  381. dbt = (DbType)Enum.Parse(typeof(DbType), t.Name);
  382. }
  383. catch
  384. {
  385. dbt = DbType.Object;
  386. }
  387. return dbt;
  388. }
  389. /// <summary>
  390. /// 使用分隔符串联表格字段的内容,如:a,b,c
  391. /// </summary>
  392. /// <param name="dt">表格</param>
  393. /// <param name="columnName">字段名称</param>
  394. /// <param name="append">增加的字符串,无则为空</param>
  395. /// <param name="splitChar">分隔符,如逗号(,)</param>
  396. /// <returns></returns>
  397. public static string ConcatColumnValue(DataTable dt, string columnName, string append, char splitChar)
  398. {
  399. string result = append;
  400. if (dt != null && dt.Rows.Count > 0)
  401. {
  402. foreach (DataRow row in dt.Rows)
  403. {
  404. result += string.Format("{0}{1}", splitChar, row[columnName]);
  405. }
  406. }
  407. return result.Trim(splitChar);
  408. }
  409. /// <summary>
  410. /// 使用逗号串联表格字段的内容,如:a,b,c
  411. /// </summary>
  412. /// <param name="dt">表格</param>
  413. /// <param name="columnName">字段名称</param>
  414. /// <param name="append">增加的字符串,无则为空</param>
  415. /// <returns></returns>
  416. public static string ConcatColumnValue(DataTable dt, string columnName, string append)
  417. {
  418. string result = append;
  419. if (dt != null && dt.Rows.Count > 0)
  420. {
  421. foreach (DataRow row in dt.Rows)
  422. {
  423. result += string.Format(",{0}", row[columnName]);
  424. }
  425. }
  426. return result.Trim(',');
  427. }
  428. /// <summary>
  429. /// 判断表格是否包含指定的全部字段名称,如果其中一个不符合则返回false
  430. /// </summary>
  431. /// <param name="dt">表格对象</param>
  432. /// <param name="columnString">字段列名称,逗号分开</param>
  433. /// <returns></returns>
  434. public static bool ContainAllColumns(DataTable dt, string columnString)
  435. {
  436. bool result = true;
  437. if (dt != null && !string.IsNullOrEmpty(columnString))
  438. {
  439. List<string> columnList = columnString.ToDelimitedList<string>(",");
  440. foreach (string columnName in columnList)
  441. {
  442. if (!string.IsNullOrEmpty(columnName) && !dt.Columns.Contains(columnName))
  443. {
  444. result = false;
  445. }
  446. }
  447. }
  448. else
  449. {
  450. result = false;
  451. }
  452. return result;
  453. }
  454. }
  455. }