KeyedCollection.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace MonoGame.Extended.Collections
  5. {
  6. public class KeyedCollection<TKey, TValue> : ICollection<TValue>
  7. {
  8. private readonly Func<TValue, TKey> _getKey;
  9. private readonly Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();
  10. public KeyedCollection(Func<TValue, TKey> getKey)
  11. {
  12. _getKey = getKey;
  13. }
  14. public TValue this[TKey key] => _dictionary[key];
  15. public ICollection<TKey> Keys => _dictionary.Keys;
  16. public ICollection<TValue> Values => _dictionary.Values;
  17. public int Count => _dictionary.Count;
  18. public bool IsReadOnly => false;
  19. IEnumerator IEnumerable.GetEnumerator()
  20. {
  21. return GetEnumerator();
  22. }
  23. public IEnumerator<TValue> GetEnumerator()
  24. {
  25. return _dictionary.Values.GetEnumerator();
  26. }
  27. public void Add(TValue item)
  28. {
  29. _dictionary.Add(_getKey(item), item);
  30. }
  31. public void Clear()
  32. {
  33. _dictionary.Clear();
  34. }
  35. public bool Contains(TValue item)
  36. {
  37. return _dictionary.ContainsKey(_getKey(item));
  38. }
  39. public void CopyTo(TValue[] array, int arrayIndex)
  40. {
  41. throw new NotSupportedException();
  42. }
  43. public bool Remove(TValue item)
  44. {
  45. return _dictionary.Remove(_getKey(item));
  46. }
  47. public bool ContainsKey(TKey key)
  48. {
  49. return _dictionary.ContainsKey(key);
  50. }
  51. public bool TryGetValue(TKey key, out TValue value)
  52. {
  53. return _dictionary.TryGetValue(key, out value);
  54. }
  55. }
  56. }