You can define your own collection type, which is built on Dictionary<TKey, TValue> and provides the GetOrAdd method (similar to GetOrAdd ConcurrentDictionary<TKey, TValue> ):
public partial class HashDictionary<T> : Dictionary<T, T> { public T GetOrAdd(T newItem) { T oldItem; if (this.TryGetValue(newItem, out oldItem)) return oldItem; this.Add(newItem, newItem); return newItem; } }
To use this, you must call:
Obj presentO = myHashDictionary.GetOrAdd(newO); if (presentO == newO) { // The item was not already present, and has been added. } else { // A collision occurred, and presentO points to the existent item. int alreadyContainedID = presentO.ID; }
To maintain compatibility with your current code, you can extend this class to implement ICollection<T> (or, preferably, ISet<T> ):
public partial class HashDictionary<T> : ICollection<T> { public void Add(T item) { this.GetOrAdd(item); } public bool Contains(T item) { return this.ContainsKey(item); } public void CopyTo(T[] array, int arrayIndex) { this.Keys.CopyTo(array, arrayIndex); } public bool IsReadOnly { get { return false; } } public new IEnumerator<T> GetEnumerator() { return this.Keys.GetEnumerator(); } }
Douglas
source share