PageRenderTime 13ms CodeModel.GetById 9ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/Main/src/DynamicDataDisplay.Maps/Set.cs

#
C# | 85 lines | 65 code | 16 blank | 4 comment | 2 complexity | e82c4c63acaad7814e41bf869d26ca33 MD5 | raw file
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Text;
 5using System.Collections;
 6using System.Diagnostics;
 7
 8namespace Microsoft.Research.DynamicDataDisplay.Charts.Maps
 9{
10	/// <summary>
11	/// Represents an unordered set of values.
12	/// </summary>
13	/// <typeparam name="T">Type of values.</typeparam>
14	[DebuggerDisplay("Count = {Count}")]
15	public sealed class Set<T> : IEnumerable<T>
16	{
17		private readonly Dictionary<T, Dummy> cache = new Dictionary<T, Dummy>();
18
19		public void Add(T item)
20		{
21			cache.Add(item, Dummy.Instance);
22		}
23
24		public bool TryAdd(T item)
25		{
26			if (!Contains(item))
27			{
28				Add(item);
29				return true;
30			}
31
32			return false;
33		}
34
35		public bool Remove(T item)
36		{
37			bool contains = cache.ContainsKey(item);
38			bool result = cache.Remove(item);
39
40			if (contains)
41			{
42				Debug.Assert(!cache.ContainsKey(item));
43			}
44			return result;
45		}
46
47		public bool Contains(T item)
48		{
49			return cache.ContainsKey(item);
50		}
51
52		private class Dummy
53		{
54			public static readonly Dummy Instance = new Dummy();
55		}
56
57		#region IEnumerable<T> Members
58
59		public IEnumerator<T> GetEnumerator()
60		{
61			return cache.Keys.GetEnumerator();
62		}
63
64		#endregion
65
66		#region IEnumerable Members
67
68		IEnumerator IEnumerable.GetEnumerator()
69		{
70			return GetEnumerator();
71		}
72
73		#endregion
74
75		public void Clear()
76		{
77			cache.Clear();
78		}
79
80		public int Count
81		{
82			get { return cache.Count; }
83		}
84	}
85}