Исходный код вики ICollection dictionary wrapper
Версия 1.1 от Alexandr Fokin на 2023/06/30 11:57
Последние авторы
| author | version | line-number | content |
|---|---|---|---|
| 1 | {{code language="c#"}} | ||
| 2 | public class CollectionDictionaryWrapper<TKey, TValue> | ||
| 3 | : ICollection<TValue>, | ||
| 4 | IReadOnlyCollection<TValue> | ||
| 5 | { | ||
| 6 | private readonly Func<TValue, TKey> _keySelector; | ||
| 7 | public IDictionary<TKey, TValue> Data { get; private set; } | ||
| 8 | |||
| 9 | |||
| 10 | public DictionaryWrapperCollection( | ||
| 11 | IDictionary<TKey, TValue> dict, | ||
| 12 | Func<TValue, TKey> keySelector | ||
| 13 | ) | ||
| 14 | { | ||
| 15 | Data = dict; | ||
| 16 | _keySelector = keySelector; | ||
| 17 | } | ||
| 18 | |||
| 19 | public DictionaryWrapperCollection( | ||
| 20 | Func<TValue, TKey> keySelector | ||
| 21 | ) | ||
| 22 | : this( | ||
| 23 | new Dictionary<TKey, TValue>(), | ||
| 24 | keySelector | ||
| 25 | ) | ||
| 26 | { } | ||
| 27 | |||
| 28 | |||
| 29 | #region ICollection | ||
| 30 | |||
| 31 | public int Count => Data.Count; | ||
| 32 | |||
| 33 | public bool IsReadOnly => Data.IsReadOnly; | ||
| 34 | |||
| 35 | public void Add(TValue item) | ||
| 36 | { | ||
| 37 | Data.Add(_keySelector(item), item); | ||
| 38 | } | ||
| 39 | |||
| 40 | public void Clear() | ||
| 41 | { | ||
| 42 | Data.Clear(); | ||
| 43 | } | ||
| 44 | |||
| 45 | public bool Contains(TValue item) | ||
| 46 | { | ||
| 47 | //Можно сделать проверку по ключу, пока сделаю по KeyValuePair | ||
| 48 | |||
| 49 | return Data | ||
| 50 | .Contains(new KeyValuePair<TKey, TValue>(_keySelector(item), item)); | ||
| 51 | } | ||
| 52 | |||
| 53 | public void CopyTo(TValue[] array, int arrayIndex) | ||
| 54 | { | ||
| 55 | Data.Values.CopyTo(array, arrayIndex); | ||
| 56 | } | ||
| 57 | |||
| 58 | public IEnumerator<TValue> GetEnumerator() | ||
| 59 | { | ||
| 60 | return Data.Values.GetEnumerator(); | ||
| 61 | } | ||
| 62 | |||
| 63 | public bool Remove(TValue item) | ||
| 64 | { | ||
| 65 | return Data.Remove(_keySelector(item)); | ||
| 66 | } | ||
| 67 | |||
| 68 | IEnumerator IEnumerable.GetEnumerator() | ||
| 69 | { | ||
| 70 | return Data.Values.GetEnumerator(); | ||
| 71 | } | ||
| 72 | |||
| 73 | #endregion | ||
| 74 | } | ||
| 75 | {{/code}} |