DictionaryExtension.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using UnityEngine;
  6. public class KVPair<Key, Value>
  7. {
  8. public Key key;
  9. public Value value;
  10. public KVPair()
  11. {
  12. }
  13. public KVPair(Key key, Value value)
  14. {
  15. this.key = key;
  16. this.value = value;
  17. }
  18. }
  19. public static class DictionaryExtension
  20. {
  21. public static bool IsAvailable<Key, Value>(this Dictionary<Key, Value> dictionary)
  22. {
  23. return dictionary != null && dictionary.Count > 0;
  24. }
  25. public static KVPair<Key, Value> GetAtIndex<Key, Value>(this Dictionary<Key, Value> dictionary, int index)
  26. {
  27. List<Key> keys = dictionary.Keys.ToList();
  28. List<Value> values = dictionary.Values.ToList();
  29. KVPair<Key, Value> kvPair = new KVPair<Key, Value>();
  30. kvPair.key = keys[index];
  31. kvPair.value = values[index];
  32. return kvPair;
  33. }
  34. public static int MyMin<Key, Value>(this Dictionary<Key, Value> dictionary, Func<Key, Value, float> func)
  35. {
  36. List<Key> keys = dictionary.Keys.ToList();
  37. List<Value> values = dictionary.Values.ToList();
  38. float min = func(keys[0], values[0]);
  39. int minIndex = 0;
  40. for (int i = 1; i < keys.Count; i++)
  41. {
  42. if (min > func(keys[i], values[i]))
  43. {
  44. min = func(keys[i], values[i]);
  45. minIndex = i;
  46. }
  47. }
  48. return minIndex;
  49. }
  50. public static int MyMax<Key, Value>(this Dictionary<Key, Value> dictionary, Func<Key, Value, float> func)
  51. {
  52. List<Key> keys = dictionary.Keys.ToList();
  53. List<Value> values = dictionary.Values.ToList();
  54. float max = func(keys[0], values[0]);
  55. int maxIndex = 0;
  56. for (int i = 1; i < keys.Count; i++)
  57. {
  58. if (max < func(keys[i], values[i]))
  59. {
  60. max = func(keys[i], values[i]);
  61. maxIndex = i;
  62. }
  63. }
  64. return maxIndex;
  65. }
  66. }