ListHelper.cs 3.1 KB

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