Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Data/3.2/ItemDictionary_T.cs @ 2396

Last change on this file since 2396 was 1529, checked in by gkronber, 16 years ago

Moved source files of plugins AdvancedOptimizationFrontEnd ... Grid into version-specific sub-folders. #576

File size: 13.8 KB
RevLine 
[187]1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Text;
5using System.Xml;
6using HeuristicLab.Core;
7
8namespace HeuristicLab.Data {
[737]9  /// <summary>
10  /// A dictionary having key-value pairs of the type <see cref="IItem"/>.
11  /// </summary>
12  /// <typeparam name="K">The type of the keys, which must implement the interface <see cref="IItem"/>.</typeparam>
13  /// <typeparam name="V">The type of the values, which must imlement the interface <see cref="IItem"/>.</typeparam>
[187]14  public class ItemDictionary<K,V> : ItemBase, IDictionary<K,V>
15    where K : IItem
16    where V : IItem{
17    private Dictionary<K, V> dict;
18
[737]19    /// <summary>
20    /// Gets the dictionary of key-value pairs.
21    /// </summary>
[187]22    public Dictionary<K, V> Dictionary {
23      get { return dict; }
24    }
25
[737]26    /// <summary>
27    /// Initializes a new instance of <see cref="ItemDictionary&lt;TKey,TValue&gt;"/>.
28    /// </summary>
29    /// <remarks>Creates a new <see cref="Dictionary"/>
30    /// having <see cref="IItem"/> as type of keys and values
31    /// and a new <see cref="IItemKeyComparer&lt;T&gt;"/> as <see cref="IEqualityComparer"/>.</remarks>
[187]32    public ItemDictionary() {
33      dict = new Dictionary<K, V>(new IItemKeyComparer<K>());
34    }
35
36    #region ItemBase Members
[737]37    /// <summary>
38    /// Creates a new instance of <see cref="ItemDictionaryView&lt;K,V&gt;"/>.
39    /// </summary>
40    /// <returns>The created instance as <see cref="ItemDictionaryView&lt;K,V&gt;"/>.</returns>
[187]41    public override IView CreateView() {
42      return new ItemDictionaryView<K,V>(this);
43    }
44
[737]45    /// <summary>
46    /// Clones the current instance and adds it to the dictionary <paramref name="clonedObjects"/>.
47    /// </summary>
48    /// <remarks>Also the keys and values in the dictionary are cloned and saved to the dictionary <paramref name="clonedObjects"/>,
49    /// when they are not already contained (deep copy).</remarks>
50    /// <param name="clonedObjects">A dictionary of all already cloned objects.</param>
51    /// <returns>The cloned instance as <see cref="ItemDictionary&lt;K,V&gt;"/>.</returns>
[187]52    public override object Clone(IDictionary<Guid, object> clonedObjects) {
53      ItemDictionary<K,V> clone = new ItemDictionary<K,V>();
54      clonedObjects.Add(Guid, clone);
55      foreach (KeyValuePair<K, V> item in dict) {
56        clone.dict.Add((K) Auxiliary.Clone(item.Key, clonedObjects), (V) Auxiliary.Clone(item.Value, clonedObjects));
57      }
58      return clone;
59    }
60
[737]61    /// <summary>
62    /// Saves the current instance as <see cref="XmlNode"/> in the specified <paramref name="document"/>.
63    /// </summary>
64    /// <remarks>Every key-value pair is saved as new child node with the tag name "KeyValuePair".<br/>
65    /// In the child node the key is saved as a new child node with the tag name "Key".<br/>
66    /// The value is also saved as new child node with the tag name "Val".
67    /// </remarks>
68    /// <param name="name">The (tag)name of the <see cref="XmlNode"/>.</param>
69    /// <param name="document">The <see cref="XmlDocument"/> where the data is saved.</param>
70    /// <param name="persistedObjects">A dictionary of all already persisted objects. (Needed to avoid cycles.)</param>
71    /// <returns>The saved <see cref="XmlNode"/>.</returns>
[187]72    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
73      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
74      foreach (KeyValuePair<K, V> item in dict) {
75        XmlNode keyNode = PersistenceManager.Persist("Key", item.Key, document, persistedObjects);
76        XmlNode valueNode = PersistenceManager.Persist("Val", item.Value, document, persistedObjects);
77        XmlNode pairNode = document.CreateNode(XmlNodeType.Element, "KeyValuePair", null);
78        pairNode.AppendChild(keyNode);
79        pairNode.AppendChild(valueNode);
80        node.AppendChild(pairNode);
81      }
82      return node;
83    }
84
[737]85    /// <summary>
86    /// Loads the persisted matrix from the specified <paramref name="node"/>.
87    /// </summary>
88    /// <remarks>All key-value pairs must be saved as child nodes of the node. <br/>
89    /// Every child node has to contain two child nodes itself, one for the key, having the tag name "Key",
90    /// and one for the value, having the tag name "Val" (see <see cref="GetXmlNode"/>).</remarks>
91    /// <param name="node">The <see cref="XmlNode"/> where the instance is saved.</param>
92    /// <param name="restoredObjects">The dictionary of all already restored objects. (Needed to avoid cycles.)</param>
[187]93    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
94      base.Populate(node, restoredObjects);
95      for (int i = 0; i < node.ChildNodes.Count; i++) {
96        K key = (K) PersistenceManager.Restore(node.ChildNodes[i].SelectSingleNode("Key"), restoredObjects);
97        V val = (V) PersistenceManager.Restore(node.ChildNodes[i].SelectSingleNode("Val"), restoredObjects);
98        dict[key] = val;
99      }
100    }
101
[737]102    /// <summary>
103    /// The string representation of the dictionary
104    /// </summary>
105    /// <returns>The elements of the dictionary as string, each key-value pair in the format
106    /// <c>Key:Value</c>, separated by a semicolon. <br/>
107    /// If the dictionary contains no entries, "Empty Dictionary" is returned.</returns>
[187]108    public override string ToString() {
109      if (dict.Count > 0) {
110        StringBuilder builder = new StringBuilder();
111        foreach (KeyValuePair<K, V> item in dict) {
112          builder.Append(item.Key.ToString());
113          builder.Append(":");
114          builder.Append(item.Value.ToString());
115          builder.Append("; ");
116        }
117        return builder.ToString();
118      } else {
119        return "Empty Dictionary";
120      }
121    }
122    #endregion
123
124    #region IDictionary<K,V> Members
125
[737]126    ///// <summary>
127    ///// Adds a new key value pair to the dictionary.
128    ///// </summary>
129    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;K,V&gt;.Add"/>
130    /// <remarks>Calls <see cref="OnItemAdded"/>.</remarks>
131    ///// <param name="key">The key to add.</param>
132    ///// <param name="value">The value to add.</param>
[187]133    public void Add(K key, V value) {
134      dict.Add(key, value);
135      OnItemAdded(key, value);
136    }
137
[737]138    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;TKey,TValue&gt;.ContainsKey"/>
[187]139    public bool ContainsKey(K key) {
140      return dict.ContainsKey(key);
141    }
142
[737]143    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;TKey,TValue&gt;.Keys"/>
[187]144    public ICollection<K> Keys {
145      get { return dict.Keys; }
146    }
147
[737]148    /// <summary>
149    /// Removes a key-value pair having the specified <paramref name="key"/>.
150    /// </summary>
151    /// <remarks>Calls <see cref="OnItemRemoved"/>.</remarks>
152    /// <param name="key">The key of the key-value pair, which should be removed.</param>
153    /// <returns><c>true</c> if the key was found and successfully removed,
154    /// <c>false</c> if the key was not found.</returns>
[187]155    public bool Remove(K key) {
156      V value = dict[key];
157      bool removed = dict.Remove(key);
158      OnItemRemoved(key, value);
159      return removed;
160    }
161
[737]162    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;K,V&gt;.TryGetValue"/>
[187]163    public bool TryGetValue(K key, out V value) {
164      return dict.TryGetValue(key, out value);
165    }
166
[737]167    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;TKey,TValue&gt;.Values"/>
[187]168    public ICollection<V> Values {
169      get { return dict.Values; }
170    }
171
[737]172    /// <summary>
173    /// Gets or sets the value of a specified <paramref name="key"/>.
174    /// </summary>
175    /// <param name="key">The key of the value which should be received or changed.</param>
176    /// <returns>The value of the <paramref name="key"/>.</returns>
[187]177    public V this[K key] {
178      get { return dict[key]; }
179      set { dict[key] = value; }
180    }
181
182    #endregion
183
184    #region ICollection<KeyValuePair<K,V>> Members
185
[737]186    /// <summary>
187    /// Adds a key-value pair to the current instance.
188    /// </summary>
189    /// <remarks>Calls <see cref="OnItemAdded"/>.</remarks>
190    /// <param name="item">The key-value pair to add.</param>
[187]191    public void Add(KeyValuePair<K, V> item) {
192      dict.Add(item.Key, item.Value);
193      OnItemAdded(item.Key, item.Value);
194    }
195
[737]196    ///// <summary>
197    ///// Empties the dictionary.
198    ///// </summary>
199    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;K,V&gt;.Clear"/>
200    /// <remarks>Calls <see cref="OnCleared"/>.</remarks>
[187]201    public void Clear() {
202      dict.Clear();
203      OnCleared();
204    }
205
[737]206    /// <summary>
207    /// Checks whether the specified key-value pair exists in the current instance of the dictionary.
208    /// </summary>
209    /// <param name="item">The key-value pair to check.</param>
210    /// <returns><c>true</c> if both, the key and the value exist in the dictionary,
211    /// <c>false</c> otherwise.</returns>
[187]212    public bool Contains(KeyValuePair<K, V> item) {
213      return (dict.ContainsKey(item.Key) && dict[item.Key].Equals(item.Value));
214    }
215
[737]216    /// <summary>
217    /// TODO
218    /// </summary>
219    /// <param name="array"></param>
220    /// <param name="arrayIndex"></param>
[187]221    public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex) {
222      throw new NotImplementedException();
223    }
224
[737]225    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;K,V&gt;.Count"/>
[187]226    public int Count {
227      get { return dict.Count; }
228    }
229
[737]230    /// <summary>
231    /// Checks whether the dictionary is read-only.
232    /// </summary>
233    /// <remarks>Always returns <c>false</c>.</remarks>
[187]234    public bool IsReadOnly {
235      get { return false; }
236    }
237
[737]238    /// <summary>
239    /// Removes the specified key-value pair.
240    /// </summary>
241    /// <remarks>Calls <see cref="OnItemRemoved"/> when the removal was successful.</remarks>
242    /// <param name="item">The key-value pair to remove.</param>
243    /// <returns><c>true</c> if the removal was successful, <c>false</c> otherwise.</returns>
[187]244    public bool Remove(KeyValuePair<K, V> item) {
245      bool removed = dict.Remove(item.Key);
246      if (removed) {
247        OnItemRemoved(item.Key, item.Value);
248      }
249      return removed;
250    }
251    #endregion
252
253    #region IEnumerable<KeyValuePair<K,V>> Members
[737]254    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;K,V&gt;.GetEnumerator"/>
[187]255    public IEnumerator<KeyValuePair<K, V>> GetEnumerator() {
256      return dict.GetEnumerator();
257    }
258    #endregion
259
260    #region IEnumerable Members
[737]261    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;K,V&gt;.GetEnumerator"/>
[187]262    IEnumerator IEnumerable.GetEnumerator() {
263      return dict.GetEnumerator();
264    }
265    #endregion
266
267    #region Event Handler
[737]268    /// <summary>
269    /// Occurs when a new item is added to the dictionary.
270    /// </summary>
[187]271    public event EventHandler<KeyValueEventArgs> ItemAdded;
[737]272    /// <summary>
273    /// Fires a new <c>ItemAdded</c> event.
274    /// </summary>
275    /// <remarks>Calls <see cref="HeuristicLab.Core.ItemBase.OnChanged"/>.</remarks>
276    /// <param name="key">The key that was added.</param>
277    /// <param name="value">The value that was added.</param>
[187]278    protected virtual void OnItemAdded(K key, V value) {
279      if (ItemAdded != null)
280        ItemAdded(this, new KeyValueEventArgs(key, value));
281      OnChanged();
282    }
283
[737]284    /// <summary>
285    /// Occurs when an item is removed from the dictionary.
286    /// </summary>
[187]287    public event EventHandler<KeyValueEventArgs> ItemRemoved;
[737]288    /// <summary>
289    /// Fires a new <c>ItemRemoved</c> event.
290    /// </summary>
291    /// <remarks>Calls <see cref="HeuristicLab.Core.ItemBase.OnChanged"/>.</remarks>
292    /// <param name="key">The key that was removed.</param>
293    /// <param name="value">The value that was removed</param>
[187]294    protected virtual void OnItemRemoved(K key, V value) {
295      if (ItemRemoved != null)
296        ItemRemoved(this, new KeyValueEventArgs(key, value));
297      OnChanged();
298    }
299
[737]300    /// <summary>
301    /// Occurs when the dictionary is emptied.
302    /// </summary>
[187]303    public event EventHandler Cleared;
[737]304    /// <summary>
305    /// Fires a new <c>Cleared</c> event.
306    /// </summary>
307    /// <remarks>Calls <see cref="HeuristicLab.Core.ItemBase.OnChanged"/>.</remarks>
[187]308    protected virtual void OnCleared() {
309      if (Cleared != null)
310        Cleared(this, new EventArgs());
311      OnChanged();
312    }
313    #endregion
314
315    #region IEqualityComparer
[737]316    /// <summary>
317    /// Compares two keys with each other.
318    /// </summary>
319    /// <typeparam name="T">The type of the keys.</typeparam>
[187]320    internal sealed class IItemKeyComparer<T> : IEqualityComparer<T>
321        where T : IItem {
[737]322      /// <summary>
323      /// Checks whether two keys are equal to each other.
324      /// </summary>
325      /// <param name="x">Key number one.</param>
326      /// <param name="y">Key number two.</param>
327      /// <returns><c>true</c> if the two keys are the same, <c>false</c> otherwise.</returns>
[187]328      public bool Equals(T x, T y) {
329        if (x is IComparable) {
330          return (((IComparable) x).CompareTo(y) == 0);
331        }
332        if (y is IComparable) {
333          return (((IComparable) y).CompareTo(x) == 0);
334        }
335        return x.Equals(y);
336      }
337
[737]338      /// <summary>
339      /// Serves as a hash function for a particular type.
340      /// </summary>
341      /// <param name="obj">The object where the hash code is searched for.</param>
342      /// <returns>A hash code for the given <paramref name="obj"/>.</returns>
[187]343      public int GetHashCode(T obj) {
344        if (obj is IObjectData) {
345          return ((IObjectData) obj).Data.GetHashCode();
346        }
347        return obj.Guid.GetHashCode();
348      }
349    }
350    #endregion
351  }
352}
Note: See TracBrowser for help on using the repository browser.