LookupX.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System.Collections;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. namespace Masuit.Tools.Systems;
  6. public class LookupX<TKey, TElement> : IEnumerable<Grouping<TKey, TElement>>
  7. {
  8. private readonly IDictionary<TKey, List<TElement>> _dictionary;
  9. public LookupX(Dictionary<TKey, List<TElement>> dic)
  10. {
  11. _dictionary = dic;
  12. }
  13. public LookupX(ConcurrentDictionary<TKey, List<TElement>> dic)
  14. {
  15. _dictionary = dic;
  16. }
  17. public IEnumerator<Grouping<TKey, TElement>> GetEnumerator()
  18. {
  19. return _dictionary.Select(pair => new Grouping<TKey, TElement>(pair.Key, pair.Value)).GetEnumerator();
  20. }
  21. IEnumerator IEnumerable.GetEnumerator()
  22. {
  23. return GetEnumerator();
  24. }
  25. public bool Contains(TKey key)
  26. {
  27. return _dictionary.ContainsKey(key);
  28. }
  29. public int Count => _dictionary.Count;
  30. public List<TElement> this[TKey key] => _dictionary.TryGetValue(key, out var value) ? value : new List<TElement>();
  31. }
  32. public class Grouping<TKey, TElement> : IEnumerable<TElement>
  33. {
  34. private readonly List<TElement> _list;
  35. internal Grouping(TKey key, List<TElement> list)
  36. {
  37. Key = key;
  38. _list = list;
  39. }
  40. public IEnumerator<TElement> GetEnumerator()
  41. {
  42. return _list.GetEnumerator();
  43. }
  44. IEnumerator IEnumerable.GetEnumerator()
  45. {
  46. return GetEnumerator();
  47. }
  48. public TKey Key { get; }
  49. public void Deconstruct(out TKey key, out List<TElement> elements)
  50. {
  51. key = Key;
  52. elements = _list;
  53. }
  54. }