Skip to content

Instantly share code, notes, and snippets.

@kntajus
Created January 31, 2013 13:54
Show Gist options
  • Save kntajus/4683016 to your computer and use it in GitHub Desktop.
Save kntajus/4683016 to your computer and use it in GitHub Desktop.
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