Created
January 31, 2013 13:54
-
-
Save kntajus/4683016 to your computer and use it in GitHub Desktop.
Multiple keys with KeyedCollection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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