ListEx.cs 2.9 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>(List<T> list)
  17. {
  18. string listString;
  19. if (list==null||list.Count<=0)
  20. {
  21. return null;
  22. }
  23. StringBuilder sb = new StringBuilder("(");
  24. switch (typeof(T).Name)
  25. {
  26. case "DateTime":
  27. case "String":
  28. foreach (var item in list)
  29. {
  30. sb.Append("'" + item + "',");
  31. }
  32. break;
  33. default:
  34. foreach (var item in list)
  35. {
  36. sb.Append(item + ",");
  37. }
  38. break;
  39. }
  40. listString = sb.ToString().TrimEnd(',')+')';
  41. return listString;
  42. }
  43. public static string GetWhereStr(List<string> whereList, string connector = "AND")
  44. {
  45. string connectStr = " " + connector + " ";
  46. var whereStr = string.Empty;
  47. for (int i = 0; i < whereList.Count; i++)
  48. {
  49. if (i == 0)
  50. {
  51. whereStr += "(" + whereList[i] + ")";
  52. }
  53. else
  54. {
  55. whereStr += connectStr + "(" + whereList[i] + ")";
  56. }
  57. }
  58. return whereStr;
  59. }
  60. public static void GetRecursions<T>(List<T> TList, PkName pkName, out List<Recursion<T>> ReList)
  61. {
  62. ReList = new List<Recursion<T>>();
  63. var nodeDict = new Dictionary<int, Recursion<T>>();
  64. foreach(var parent in TList)
  65. {
  66. int value = Convert.ToInt32(parent.GetType().GetProperty(pkName.MainField).GetValue(parent));
  67. var recursion = new Recursion<T>()
  68. {
  69. data = parent
  70. };
  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. }