ListHelper.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System.Collections;
  2. namespace VberZero.Tools.StringModel;
  3. public static class ListHelper
  4. {
  5. /// <summary>
  6. /// 自定义Distinct扩展方法
  7. /// </summary>
  8. /// <typeparam name="T">要去重的对象类</typeparam>
  9. /// <typeparam name="TC">自定义去重的字段类型</typeparam>
  10. /// <param name="source">要去重的对象</param>
  11. /// <param name="getField">获取自定义去重字段的委托</param>
  12. /// <returns></returns>
  13. public static IEnumerable<T> VzDistinct<T, TC>(this IEnumerable<T> source, Func<T, TC> getField)
  14. {
  15. return source.Distinct(new Compare<T, TC>(getField));
  16. }
  17. /// <summary>
  18. /// 合并字典
  19. /// </summary>
  20. /// <typeparam name="T"></typeparam>
  21. /// <param name="first">字典1</param>
  22. /// <param name="second">字典2</param>
  23. /// <param name="isCover">字典2是否覆盖字典1,默认 true</param>
  24. /// <returns></returns>
  25. public static Dictionary<string, T> MergeDictionary<T>(this Dictionary<string, T>? first, Dictionary<string, T>? second, bool isCover = true)
  26. {
  27. first ??= new Dictionary<string, T>();
  28. if (second == null) return first;
  29. foreach (string key in second.Keys)
  30. {
  31. if (first.ContainsKey(key))
  32. {
  33. if (isCover)
  34. {
  35. first[key] = second[key];
  36. }
  37. }
  38. else
  39. {
  40. first.Add(key, second[key]);
  41. }
  42. }
  43. return first;
  44. }
  45. /// <summary>
  46. /// 合并字典
  47. /// </summary>
  48. /// <param name="first">字典1</param>
  49. /// <param name="second">字典2</param>
  50. /// <param name="isCover">字典2是否覆盖字典1,默认 true</param>
  51. /// <returns></returns>
  52. public static Hashtable MergeHashtable(this Hashtable? first, Hashtable? second, bool isCover = true)
  53. {
  54. first ??= new Hashtable();
  55. if (second == null) return first;
  56. foreach (string key in second.Keys)
  57. {
  58. if (first.ContainsKey(key))
  59. {
  60. if (isCover)
  61. {
  62. first[key] = second[key];
  63. }
  64. }
  65. else
  66. {
  67. first.Add(key, second[key]);
  68. }
  69. }
  70. return first;
  71. }
  72. }
  73. public class Compare<T, TC> : IEqualityComparer<T>
  74. {
  75. private Func<T, TC> GetField { get; }
  76. public Compare(Func<T, TC> getField)
  77. {
  78. GetField = getField;
  79. }
  80. public bool Equals(T? x, T? y)
  81. {
  82. return y != null && x != null && EqualityComparer<TC>.Default.Equals(GetField(x), GetField(y));
  83. }
  84. public int GetHashCode(T obj)
  85. {
  86. return EqualityComparer<TC>.Default.GetHashCode(GetField(obj)!);
  87. }
  88. }