public struct HashtableKeyPair<T, U>
{
T key;
U val;
public HashtableKeyPair(T key, U val)
{
this.key = key;
this.val = val;
}
public T Key { get { return key; } }
public U Value { get { return val; } }
}
public class Hashtable<T, U>: System.Collections.Hashtable
{
public Hashtable() : base() { }
public Hashtable(IEnumerable<HashtableKeyPair<T, U>?> keyPairs)
{
foreach (HashtableKeyPair<T, U>? keyPair in keyPairs)
if (keyPair.HasValue)
this[keyPair.Value.Key] = keyPair.Value.Value;
}
public IEnumerable<HashtableKeyPair<T, U>> KeyPairs
{
get
{
foreach (HashtableKeyPair<T, U> keyPair in base.Values)
yield return keyPair;
}
}
public U this[T key]
{
get { return ((HashtableKeyPair<T, U>)base[key]).Value; }
set
{
base[key] = new HashtableKeyPair<T, U>(key, value);
}
}
public HashtableKeyPair<T, U>? this[T key, Predicate<HashtableKeyPair<T, U>?> match]
{
get
{
if (base[key] != null)
{
HashtableKeyPair<T, U> obj = (HashtableKeyPair<T, U>)base[key];
if (match(obj))
return obj;
}
return null;
}
}
public Hashtable<T, U> GetMatchedHashtable(Predicate<HashtableKeyPair<T, U>?> match)
{
return new Hashtable<T, U>(Match(match));
}
public IEnumerable<HashtableKeyPair<T, U>?> Match(Predicate<HashtableKeyPair<T, U>?> match)
{
foreach (T key in Keys)
if (this[key, match].HasValue)
yield return this[key, match].Value;
}
public void Remove(T key)
{
base[key] = null;
}
private Predicate<HashtableKeyPair<T, U>?> hasValues = delegate(HashtableKeyPair<T, U>? obj) { return obj.HasValue; };
public void Compact()
{
Hashtable<T, U> hashtable = new Hashtable<T, U>(Match(hasValues));
base.Clear();
foreach (HashtableKeyPair<T, U> keyPair in hashtable.KeyPairs)
this[keyPair.Key] = keyPair.Value;
}
}
Hashtable<int, int> myhashtable = new Hashtable<int, int>();
myhashtable[0] = 1;
myhashtable[1] = 4;
myhashtable[2] = 9;
myhashtable[3] = 16;
Predicate<HashtableKeyPair<int, int>?> even = delegate(HashtableKeyPair<int, int>? obj) { return obj.HasValue && (obj.Value.Value % 2 == 1) == true; };
foreach (HashtableKeyPair<int, int> keyPair in myhashtable.GetMatchedHashtable(even).KeyPairs)
{
myhashtable.Remove(keyPair.Key);
}
myhashtable.Compact();