//****************************** // Written by Peter Golde // Copyright (c) 2004-2005, Wintellect // // Use and restribution of this code is subject to the license agreement // contained in the file "License.txt" accompanying this file. //****************************** using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Wintellect.PowerCollections { /// /// MultiDictionaryBase is a base class that can be used to more easily implement a class /// that associates multiple values to a single key. The class implements the generic /// IDictionary<TKey, ICollection<TValue>> interface. The resulting collection /// is read-only -- items cannot be added or removed. /// /// /// To use ReadOnlyMultiDictionaryBase as a base class, the derived class must override /// Count, Contains(TKey,TValue), EnumerateKeys, and TryEnumerateValuesForKey . /// /// The key type of the dictionary. /// The value type of the dictionary. [Serializable] [DebuggerDisplay("{DebuggerDisplayString()}")] public abstract class ReadOnlyMultiDictionaryBase : ReadOnlyCollectionBase>>, IDictionary> { /// /// Creates a new ReadOnlyMultiDictionaryBase. /// protected ReadOnlyMultiDictionaryBase() { } /// /// Throws an NotSupportedException stating that this collection cannot be modified. /// private void MethodModifiesCollection() { throw new NotSupportedException(string.Format(Strings.CannotModifyCollection, Util.SimpleClassName(this.GetType()))); } /// /// Gets the number of keys in the dictionary. This property must be overridden /// in the derived class. /// public abstract override int Count { get; } /// /// Enumerate all the keys in the dictionary. This method must be overridden by a derived /// class. /// /// An IEnumerator<TKey> that enumerates all of the keys in the collection that /// have at least one value associated with them. protected abstract IEnumerator EnumerateKeys(); /// /// Enumerate all of the values associated with a given key. This method must be overridden /// by the derived class. If the key exists and has values associated with it, an enumerator for those /// values is returned throught . If the key does not exist, false is returned. /// /// The key to get values for. /// If true is returned, this parameter receives an enumerators that /// enumerates the values associated with that key. /// True if the key exists and has values associated with it. False otherwise. protected abstract bool TryEnumerateValuesForKey(TKey key, out IEnumerator values); /// /// Implements IDictionary<TKey, IEnumerable<TValue>>.Add. If the /// key is already present, and ArgumentException is thrown. Otherwise, a /// new key is added, and new values are associated with that key. /// /// Key to add. /// Values to associate with that key. /// The key is already present in the dictionary. void IDictionary>.Add(TKey key, ICollection values) { MethodModifiesCollection(); } /// /// Removes a key from the dictionary. This method must be overridden in the derived class. /// /// Key to remove from the dictionary. /// True if the key was found, false otherwise. bool IDictionary>.Remove(TKey key) { MethodModifiesCollection(); return false; // never reached. } /// /// Determines if this dictionary contains a key equal to . If so, all the values /// associated with that key are returned through the values parameter. This method must be /// overridden by the derived class. /// /// The key to search for. /// Returns all values associated with key, if true was returned. /// True if the dictionary contains key. False if the dictionary does not contain key. bool IDictionary>.TryGetValue(TKey key, out ICollection values) { if (ContainsKey(key)) { values = this[key]; return true; } else { values = null; return false; } } /// /// Determines whether a given key is found in the dictionary. /// /// The default implementation simply calls TryGetValue. /// It may be appropriate to override this method to /// provide a more efficient implementation. /// Key to look for in the dictionary. /// True if the key is present in the dictionary. public virtual bool ContainsKey(TKey key) { IEnumerator values; return TryEnumerateValuesForKey(key, out values); } /// /// Determines if this dictionary contains a key-value pair equal to and /// . The dictionary is not changed. This method must be overridden in the derived class. /// /// The key to search for. /// The value to search for. /// True if the dictionary has associated with . public abstract bool Contains(TKey key, TValue value); /// /// Determines if this dictionary contains the given key and all of the values associated with that key.. /// /// A key and collection of values to search for. /// True if the dictionary has associated all of the values in .Value with .Key. public override bool Contains(KeyValuePair> pair) { foreach (TValue val in pair.Value) { if (!Contains(pair.Key, val)) return false; } return true; } // Cache the equality comparer after we get it the first time. private volatile IEqualityComparer valueEqualityComparer; /// /// If the derived class does not use the default comparison for values, this /// methods should be overridden to compare two values for equality. This is /// used for the correct implementation of ICollection.Contains on the Values /// and KeyValuePairs collections. /// /// First value to compare. /// Second value to compare. /// True if the values are equal. protected virtual bool EqualValues(TValue value1, TValue value2) { if (valueEqualityComparer == null) valueEqualityComparer = EqualityComparer.Default; return valueEqualityComparer.Equals(value1, value2); } /// /// Gets a count of the number of values associated with a key. The /// default implementation is slow; it enumerators all of the values /// (using TryEnumerateValuesForKey) to count them. A derived class /// may be able to supply a more efficient implementation. /// /// The key to count values for. /// The number of values associated with . protected virtual int CountValues(TKey key) { int count = 0; IEnumerator enumValues; if (TryEnumerateValuesForKey(key, out enumValues)) { using (enumValues) { while (enumValues.MoveNext()) count += 1; } } return count; } /// /// Gets a total count of values in the collection. This default implementation /// is slow; it enumerates all of the keys in the dictionary and calls CountValues on each. /// A derived class may be able to supply a more efficient implementation. /// /// The total number of values associated with all keys in the dictionary. protected virtual int CountAllValues() { int count = 0; using (IEnumerator enumKeys = EnumerateKeys()) { while (enumKeys.MoveNext()) { TKey key = enumKeys.Current; count += CountValues(key); } } return count; } /// /// Gets a read-only collection all the keys in this dictionary. /// /// An readonly ICollection<TKey> of all the keys in this dictionary. public virtual ICollection Keys { get { return new KeysCollection(this); } } /// /// Gets a read-only collection of all the values in the dictionary. /// /// A read-only ICollection<TValue> of all the values in the dictionary. public virtual ICollection Values { get { return new ValuesCollection(this); } } /// /// Gets a read-only collection of all the value collections in the dictionary. /// /// A read-only ICollection<IEnumerable<TValue>> of all the values in the dictionary. ICollection> IDictionary>.Values { get { return new EnumerableValuesCollection(this); } } /// /// Gets a read-only collection of all key-value pairs in the dictionary. If a key has multiple /// values associated with it, then a key-value pair is present for each value associated /// with the key. /// public virtual ICollection> KeyValuePairs { get { return new KeyValuePairsCollection(this); } } /// /// Returns a collection of all of the values in the dictionary associated with . /// If the key is not present in the dictionary, an ICollection with no /// values is returned. The returned ICollection is read-only. /// /// The key to get the values associated with. /// An ICollection<TValue> with all the values associated with . public virtual ICollection this[TKey key] { get { return new ValuesForKeyCollection(this, key); } } /// /// Gets a collection of all the values in the dictionary associated with . /// If the key is not present in the dictionary, a KeyNotFound exception is thrown. /// /// The key to get the values associated with. /// An IEnumerable<TValue> that enumerates all the values associated with . /// The given key is not present in the dictionary. /// The set accessor is called. ICollection IDictionary>.this[TKey key] { get { if (ContainsKey(key)) return new ValuesForKeyCollection(this, key); else throw new KeyNotFoundException(Strings.KeyNotFound); } set { MethodModifiesCollection(); } } /// /// Shows the string representation of the dictionary. The string representation contains /// a list of the mappings in the dictionary. /// /// The string representation of the dictionary. public override string ToString() { bool firstItem = true; System.Text.StringBuilder builder = new System.Text.StringBuilder(); builder.Append("{"); // Call ToString on each item and put it in. foreach (KeyValuePair> pair in this) { if (!firstItem) builder.Append(", "); if (pair.Key == null) builder.Append("null"); else builder.Append(pair.Key.ToString()); builder.Append("->"); // Put all values in a parenthesized list. builder.Append('('); bool firstValue = true; foreach (TValue val in pair.Value) { if (!firstValue) builder.Append(","); if (val == null) builder.Append("null"); else builder.Append(val.ToString()); firstValue = false; } builder.Append(')'); firstItem = false; } builder.Append("}"); return builder.ToString(); } /// /// Display the contents of the dictionary in the debugger. This is intentionally private, it is called /// only from the debugger due to the presence of the DebuggerDisplay attribute. It is similar /// format to ToString(), but is limited to 250-300 characters or so, so as not to overload the debugger. /// /// The string representation of the items in the collection, similar in format to ToString(). new internal string DebuggerDisplayString() { const int MAXLENGTH = 250; bool firstItem = true; System.Text.StringBuilder builder = new System.Text.StringBuilder(); builder.Append("{"); // Call ToString on each item and put it in. foreach (KeyValuePair> pair in this) { if (builder.Length >= MAXLENGTH) { builder.Append(", ..."); break; } if (!firstItem) builder.Append(", "); if (pair.Key == null) builder.Append("null"); else builder.Append(pair.Key.ToString()); builder.Append("->"); // Put all values in a parenthesized list. builder.Append('('); bool firstValue = true; foreach (TValue val in pair.Value) { if (!firstValue) builder.Append(","); if (val == null) builder.Append("null"); else builder.Append(val.ToString()); firstValue = false; } builder.Append(')'); firstItem = false; } builder.Append("}"); return builder.ToString(); } /// /// Enumerate all the keys in the dictionary, and for each key, the collection of values for that key. /// /// An enumerator to enumerate all the key, ICollection<value> pairs in the dictionary. public override IEnumerator>> GetEnumerator() { using (IEnumerator enumKeys = EnumerateKeys()) { while (enumKeys.MoveNext()) { TKey key = enumKeys.Current; yield return new KeyValuePair>(key, new ValuesForKeyCollection(this, key)); } } } #region Keys and Values collections /// /// A private class that provides the ICollection<TValue> for a particular key. This is the collection /// that is returned from the indexer. The collections is read-write, live, and can be used to add, remove, /// etc. values from the multi-dictionary. /// [Serializable] private sealed class ValuesForKeyCollection : ReadOnlyCollectionBase { private ReadOnlyMultiDictionaryBase myDictionary; private TKey key; /// /// Constructor. Initializes this collection. /// /// Dictionary we're using. /// The key we're looking at. public ValuesForKeyCollection(ReadOnlyMultiDictionaryBase myDictionary, TKey key) { this.myDictionary = myDictionary; this.key = key; } /// /// Get the number of values associated with the key. /// public override int Count { get { return myDictionary.CountValues(key); } } /// /// A simple function that returns an IEnumerator<TValue> that /// doesn't yield any values. A helper. /// /// An IEnumerator<TValue> that yields no values. private IEnumerator NoValues() { yield break; } /// /// Enumerate all the values associated with key. /// /// An IEnumerator<TValue> that enumerates all the values associated with key. public override IEnumerator GetEnumerator() { IEnumerator values; if (myDictionary.TryEnumerateValuesForKey(key, out values)) return values; else return NoValues(); } /// /// Determines if the given values is associated with key. /// /// Value to check for. /// True if value is associated with key, false otherwise. public override bool Contains(TValue item) { return myDictionary.Contains(key, item); } } /// /// A private class that implements ICollection<TKey> and ICollection for the /// Keys collection. The collection is read-only. /// [Serializable] private sealed class KeysCollection : ReadOnlyCollectionBase { private ReadOnlyMultiDictionaryBase myDictionary; /// /// Constructor. /// /// The dictionary this is associated with. public KeysCollection(ReadOnlyMultiDictionaryBase myDictionary) { this.myDictionary = myDictionary; } public override int Count { get { return myDictionary.Count; } } public override IEnumerator GetEnumerator() { return myDictionary.EnumerateKeys(); } public override bool Contains(TKey key) { return myDictionary.ContainsKey(key); } } /// /// A private class that implements ICollection<TValue> and ICollection for the /// Values collection. The collection is read-only. /// [Serializable] private sealed class ValuesCollection : ReadOnlyCollectionBase { private ReadOnlyMultiDictionaryBase myDictionary; public ValuesCollection(ReadOnlyMultiDictionaryBase myDictionary) { this.myDictionary = myDictionary; } public override int Count { get { return myDictionary.CountAllValues(); } } public override IEnumerator GetEnumerator() { using (IEnumerator enumKeys = myDictionary.EnumerateKeys()) { while (enumKeys.MoveNext()) { TKey key = enumKeys.Current; IEnumerator enumValues; if (myDictionary.TryEnumerateValuesForKey(key, out enumValues)) { using (enumValues) { while (enumValues.MoveNext()) yield return enumValues.Current; } } } } } public override bool Contains(TValue value) { foreach (TValue v in this) { if (myDictionary.EqualValues(v, value)) return true; } return false; } } /// /// A private class that implements ICollection<IEnumerable<TValue>> and ICollection for the /// Values collection on IDictionary. The collection is read-only. /// [Serializable] private sealed class EnumerableValuesCollection : ReadOnlyCollectionBase> { private ReadOnlyMultiDictionaryBase myDictionary; public EnumerableValuesCollection(ReadOnlyMultiDictionaryBase myDictionary) { this.myDictionary = myDictionary; } public override int Count { get { return myDictionary.Count; } } public override IEnumerator> GetEnumerator() { using (IEnumerator enumKeys = myDictionary.EnumerateKeys()) { while (enumKeys.MoveNext()) { TKey key = enumKeys.Current; yield return new ValuesForKeyCollection(myDictionary, key); } } } public override bool Contains(ICollection values) { if (values == null) return false; TValue[] valueArray = Algorithms.ToArray(values); foreach (ICollection v in this) { if (v.Count != valueArray.Length) continue; // First check in order for efficiency. if (Algorithms.EqualCollections(v, values, myDictionary.EqualValues)) return true; // Now check not in order. We can't use Algorithms.EqualSets, because we don't // have an IEqualityComparer, just the ability to compare for equality. Unfortunately this is N squared, // but there isn't a good choice here. We don't really expect this method to be used much. bool[] found = new bool[valueArray.Length]; foreach (TValue x in v) { for (int i = 0; i < valueArray.Length; ++i) { if (!found[i] && myDictionary.EqualValues(x, valueArray[i])) found[i] = true; } } if (Array.IndexOf(found, false) < 0) return true; // every item was found. The sets must be equal. } return false; } } /// /// A private class that implements ICollection<KeyValuePair<TKey,TValue>> and ICollection for the /// KeyValuePairs collection. The collection is read-only. /// [Serializable] private sealed class KeyValuePairsCollection : ReadOnlyCollectionBase> { private ReadOnlyMultiDictionaryBase myDictionary; public KeyValuePairsCollection(ReadOnlyMultiDictionaryBase myDictionary) { this.myDictionary = myDictionary; } public override int Count { get { return myDictionary.CountAllValues(); } } public override IEnumerator> GetEnumerator() { using (IEnumerator enumKeys = myDictionary.EnumerateKeys()) { while (enumKeys.MoveNext()) { TKey key = enumKeys.Current; IEnumerator enumValues; if (myDictionary.TryEnumerateValuesForKey(key, out enumValues)) { using (enumValues) { while (enumValues.MoveNext()) yield return new KeyValuePair(key, enumValues.Current); } } } } } public override bool Contains(KeyValuePair pair) { return myDictionary[pair.Key].Contains(pair.Value); } } #endregion } }