2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Collections.Immutable;
9 public class ListDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue>
11 private readonly ImmutableDictionary<TKey, int> keyToIndex;
12 private readonly IReadOnlyList<TValue> list;
14 public ListDictionary(IReadOnlyList<TValue> list,
int len, Func<int, TKey> keyFunc)
17 var keyToIndex =
new Dictionary<TKey, int>();
18 for (
int i = 0; i < len; i++)
20 keyToIndex.Add(keyFunc(i), i);
23 this.keyToIndex = keyToIndex.ToImmutableDictionary();
28 foreach (var kvp
in keyToIndex)
30 yield
return new KeyValuePair<TKey, TValue>(kvp.Key, list[kvp.Value]);
36 public int Count => keyToIndex.Count;
37 public bool ContainsKey(TKey key) => keyToIndex.ContainsKey(key);
41 if (keyToIndex.TryGetValue(key, out
int index))
46 value =
default(TValue);
50 public TValue
this[TKey key] => list[keyToIndex[key]];
52 public IEnumerable<TKey>
Keys => keyToIndex.Keys;
53 public IEnumerable<TValue>
Values => keyToIndex.Values.Select(i => list[i]);
ListDictionary(IReadOnlyList< TValue > list, int len, Func< int, TKey > keyFunc)
IEnumerator< KeyValuePair< TKey, TValue > > GetEnumerator()
IEnumerable< TValue > Values
bool ContainsKey(TKey key)
bool TryGetValue(TKey key, out TValue value)