ExtensionDictionary.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using UnityEngine;
  2. using System;
  3. using System.Linq;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. public static class ExtensionDictionary
  7. {
  8. public static T2 Random<T1, T2>(this Dictionary<T1, T2> dic, bool remove = false, Func<T2,bool> func = null)
  9. {
  10. int antiCrush = 0;
  11. while (true)
  12. {
  13. if (antiCrush++>10000)
  14. {
  15. throw new Exception();
  16. }
  17. int index = UnityEngine.Random.Range(0, dic.Count);
  18. T1 resultKey = dic.Keys.ToList()[index];
  19. T2 resultValue = dic.Values.ToList()[index];
  20. if (func != null)
  21. {
  22. if (!func(resultValue))
  23. {
  24. continue;
  25. }
  26. }
  27. if (remove)
  28. {
  29. dic.Remove(resultKey);
  30. return resultValue;
  31. }
  32. else
  33. {
  34. return resultValue;
  35. }
  36. }
  37. }
  38. public static bool UniqueAdd<T1, T2>(this Dictionary<T1, T2> dic, T1 t1, T2 t2)
  39. {
  40. if (dic.ContainsKey(t1))
  41. {
  42. return false;
  43. }
  44. else
  45. {
  46. dic.Add(t1, t2);
  47. return true;
  48. }
  49. }
  50. }