ListEx.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. recursion.value = Convert.ToInt32(parent.GetType().GetProperty(pkName.MainField).GetValue(parent));
  72. recursion.text = Convert.ToString(parent.GetType().GetProperty(pkName.MainName).GetValue(parent));
  73. nodeDict[value] = recursion;
  74. }
  75. // 添加子节点
  76. foreach (var child in TList)
  77. {
  78. int value = Convert.ToInt32(child.GetType().GetProperty(pkName.MainField).GetValue(child));
  79. int parentid = Convert.ToInt32(child.GetType().GetProperty(pkName.ParentField).GetValue(child));
  80. if (parentid == 0)
  81. {
  82. ReList.Add(nodeDict[value]);
  83. }else if (nodeDict.TryGetValue(parentid, out var parentRecursion))
  84. {
  85. parentRecursion.AddChild(nodeDict[value]);
  86. }
  87. }
  88. }
  89. }
  90. }