Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Multiple keys with KeyedCollection
namespace Diuturnal.Utility {
[Serializable]
public abstract class DoubleKeyedCollection<TKey, TSecondKey, TItem>
: KeyedCollection<TKey, TItem> {
private Dictionary<TSecondKey, TKey> _secondKeyIndex =
new Dictionary<TSecondKey, TKey>();
public TItem GetItem(TSecondKey secondKey) {
return this[_secondKeyIndex[secondKey]];
}
protected abstract TSecondKey GetSecondKeyForItem(TItem item);
protected override void InsertItem(int index, TItem item) {
base.InsertItem(index, item);
AddSecondKeyIndex(this.GetSecondKeyForItem(item),
this.GetKeyForItem(item));
}
protected override void RemoveItem(int index) {
RemoveSecondKeyIndex(this.GetSecondKeyForItem(this[index]));
base.RemoveItem(index);
}
protected override void SetItem(int index, TItem item) {
RemoveSecondKeyIndex(this.GetSecondKeyForItem(this[index]));
base.SetItem(index, item);
AddSecondKeyIndex(this.GetSecondKeyForItem(item),
this.GetKeyForItem(item));
}
protected override void ClearItems() {
base.ClearItems();
_secondKeyIndex.Clear();
}
private void AddSecondKeyIndex(TSecondKey secondKey, TKey key) {
_secondKeyIndex.Add(secondKey, key);
}
private void RemoveSecondKeyIndex(TSecondKey secondKey) {
_secondKeyIndex.Remove(secondKey);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.