ListEx.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using JLHHJSvr.Com.Model;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Data.SqlClient;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.Text;
  9. namespace DirectService.Tools
  10. {
  11. internal static class ListEx
  12. {
  13. /// <summary>
  14. /// 把列表转换为(*,*,*,*,...)字符串,空列表返回null
  15. /// </summary>
  16. public static string getString<T>(IEnumerable<T> list)
  17. {
  18. string listString;
  19. if (list == null || !list.Any())
  20. {
  21. return null;
  22. }
  23. StringBuilder sb = new StringBuilder("(");
  24. if (typeof(T).IsAssignableFrom(typeof(string)) || typeof(T).IsAssignableFrom(typeof(DateTime)))
  25. {
  26. foreach (var item in list)
  27. {
  28. sb.Append("'" + item + "',");
  29. }
  30. }
  31. else
  32. {
  33. foreach (var item in list)
  34. {
  35. sb.Append(item + ",");
  36. }
  37. }
  38. listString = sb.ToString().TrimEnd(',') + ')';
  39. return listString;
  40. }
  41. public static string GetWhereStr(List<string> whereList, string connector = "AND")
  42. {
  43. string connectStr = " " + connector + " ";
  44. var whereStr = string.Empty;
  45. for (int i = 0; i < whereList.Count; i++)
  46. {
  47. if (i == 0)
  48. {
  49. whereStr += "(" + whereList[i] + ")";
  50. }
  51. else
  52. {
  53. whereStr += connectStr + "(" + whereList[i] + ")";
  54. }
  55. }
  56. return whereStr;
  57. }
  58. public static void GetRecursions<T>(List<T> TList, PkName pkName, out List<Recursion<T>> ReList)
  59. {
  60. ReList = new List<Recursion<T>>();
  61. var nodeDict = new Dictionary<int, Recursion<T>>();
  62. foreach(var parent in TList)
  63. {
  64. int value = Convert.ToInt32(parent.GetType().GetProperty(pkName.MainField).GetValue(parent));
  65. var recursion = new Recursion<T>()
  66. {
  67. data = parent
  68. };
  69. recursion.value = Convert.ToInt32(parent.GetType().GetProperty(pkName.MainField).GetValue(parent));
  70. recursion.text = Convert.ToString(parent.GetType().GetProperty(pkName.MainName).GetValue(parent));
  71. nodeDict[value] = recursion;
  72. }
  73. // 添加子节点
  74. foreach (var child in TList)
  75. {
  76. int value = Convert.ToInt32(child.GetType().GetProperty(pkName.MainField).GetValue(child));
  77. int parentid = Convert.ToInt32(child.GetType().GetProperty(pkName.ParentField).GetValue(child));
  78. if (parentid == 0)
  79. {
  80. ReList.Add(nodeDict[value]);
  81. }else if (nodeDict.TryGetValue(parentid, out var parentRecursion))
  82. {
  83. parentRecursion.AddChild(nodeDict[value]);
  84. }
  85. }
  86. }
  87. }
  88. }