DictionaryEx.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. namespace FF8
  4. {
  5. /// <summary>
  6. /// class to add function to dictionary
  7. /// </summary>
  8. /// <see cref="https://stackoverflow.com/questions/22595655/how-to-do-a-dictionary-reverse-lookup"/>
  9. /// <seealso cref="https://stackoverflow.com/questions/6050633/why-doesnt-dictionary-have-addrange"/>
  10. public static class DictionaryEx
  11. {
  12. #region Methods
  13. /// <summary>
  14. /// Reverses Key and Value of dictionary.
  15. /// </summary>
  16. /// <typeparam name="TKey"></typeparam>
  17. /// <typeparam name="TValue"></typeparam>
  18. /// <param name="source"></param>
  19. /// <returns></returns>
  20. public static Dictionary<TValue, TKey> Reverse<TKey, TValue>(this IDictionary<TKey, TValue> source)
  21. {
  22. Dictionary<TValue, TKey> dictionary = new Dictionary<TValue, TKey>();
  23. foreach (KeyValuePair<TKey, TValue> entry in source)
  24. {
  25. if (!dictionary.ContainsKey(entry.Value))
  26. dictionary.Add(entry.Value, entry.Key);
  27. }
  28. return dictionary;
  29. }
  30. public static void AddRangeOverride<TKey, TValue>(this Dictionary<TKey, TValue> dic, Dictionary<TKey, TValue> dicToAdd)
  31. {
  32. dicToAdd.ForEach(x => dic[x.Key] = x.Value);
  33. }
  34. public static void AddRangeNewOnly<TKey, TValue>(this Dictionary<TKey, TValue> dic, Dictionary<TKey, TValue> dicToAdd)
  35. {
  36. dicToAdd.ForEach(x => { if (!dic.ContainsKey(x.Key)) dic.Add(x.Key, x.Value); });
  37. }
  38. public static void AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dic, Dictionary<TKey, TValue> dicToAdd)
  39. {
  40. dicToAdd.ForEach(x => dic.Add(x.Key, x.Value));
  41. }
  42. public static bool ContainsKeys<TKey, TValue>(this Dictionary<TKey, TValue> dic, IEnumerable<TKey> keys)
  43. {
  44. bool result = false;
  45. keys.ForEachOrBreak((x) => { result = dic.ContainsKey(x); return result; });
  46. return result;
  47. }
  48. public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
  49. {
  50. foreach (var item in source)
  51. action(item);
  52. }
  53. public static void ForEachOrBreak<T>(this IEnumerable<T> source, Func<T, bool> func)
  54. {
  55. foreach (var item in source)
  56. {
  57. bool result = func(item);
  58. if (result) break;
  59. }
  60. }
  61. #endregion Methods
  62. }
  63. }