17 using System.Collections.Generic;
20 namespace erminas.SmartAPI.Utils.CachedCollections
25 public class IndexedCachedList<TK, T> : CachedList<T>, IIndexedCachedList<TK, T> where T : class
27 private readonly Func<T, TK> _indexFunc;
28 private Dictionary<TK, T> _index =
new Dictionary<TK, T>();
30 public IndexedCachedList(Func<List<T>> retrieveFunc, Func<T, TK> indexFunc,
Caching caching) : base(retrieveFunc, caching)
32 _indexFunc = indexFunc;
35 protected IndexedCachedList(Func<T, TK> indexFunc,
Caching caching) : base(caching)
37 _indexFunc = indexFunc;
40 protected override List<T> List
53 _index = value.ToDictionary(_indexFunc);
55 catch (ArgumentException e)
57 ThrowDuplicatesException(value, e);
64 private void ThrowDuplicatesException(List<T> value, ArgumentException e)
66 var duplicates = value.GroupBy(_indexFunc)
67 .Where(g => g.Count() > 1)
70 throw new Exception(
"Duplicate key/s: " +
string.Join(
", ", duplicates), e);
73 #region IIndexedCachedList<TK,T> Members
75 public bool ContainsKey(TK key)
78 return _index.ContainsKey(key);
86 return IsCachingEnabled
92 catch (InvalidOperationException e)
94 throw new KeyNotFoundException(String.Format(
"No element with key '{0}' found", key), e);
98 public override bool IsCachingEnabled
102 if (value && !base.IsCachingEnabled && List != null)
106 _index = List.ToDictionary(_indexFunc);
108 catch (ArgumentException e)
110 ThrowDuplicatesException(List, e);
115 if (!value && base.IsCachingEnabled)
121 base.IsCachingEnabled = value;
125 public T
this[TK key]
127 get {
return Get(key); }
130 public new IIndexedCachedList<TK, T> Refreshed()
136 public bool TryGet(TK key, out T obj)
143 EnsureListIsLoaded();
144 if (IsCachingEnabled)
146 return _index.TryGetValue(key, out obj);
149 obj = List.FirstOrDefault(
155 public void WaitFor(Predicate<IIndexedCachedList<TK, T>> predicate, TimeSpan maxWait, TimeSpan retryPeriod)
157 Wait.For(() => predicate(Refreshed()), maxWait, retryPeriod);