Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive_Milestone3/sources/HeuristicLab.Data/3.3/ItemDictionary_T.cs @ 4067

Last change on this file since 4067 was 1823, checked in by epitzer, 16 years ago

Namespace refactoring: rename formatters & decomposers -> primitive and composite serializers. (#603)

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