Last active
September 18, 2015 01:46
-
-
Save melvinlee/1843d4ac3e6f2c48ce6b to your computer and use it in GitHub Desktop.
Generic Dictionary Mapping Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Collections.Generic; | |
| using System.Linq; | |
| namespace Sample | |
| { | |
| public class ConnectionMapping<T> | |
| { | |
| private readonly Dictionary<T, HashSet<string>> _connections = | |
| new Dictionary<T, HashSet<string>>(); | |
| public int Count | |
| { | |
| get | |
| { | |
| return _connections.Count; | |
| } | |
| } | |
| public void Add(T key, string connectionId) | |
| { | |
| lock (_connections) | |
| { | |
| HashSet<string> connections; | |
| if (!_connections.TryGetValue(key, out connections)) | |
| { | |
| connections = new HashSet<string>(); | |
| _connections.Add(key, connections); | |
| } | |
| lock (connections) | |
| { | |
| connections.Add(connectionId); | |
| } | |
| } | |
| } | |
| public IEnumerable<string> Get(T key) | |
| { | |
| HashSet<string> connections; | |
| if (_connections.TryGetValue(key, out connections)) | |
| { | |
| return connections; | |
| } | |
| return Enumerable.Empty<string>(); | |
| } | |
| public void Remove(T key, string connectionId) | |
| { | |
| lock (_connections) | |
| { | |
| HashSet<string> connections; | |
| if (!_connections.TryGetValue(key, out connections)) | |
| { | |
| return; | |
| } | |
| lock (connections) | |
| { | |
| connections.Remove(connectionId); | |
| if (connections.Count == 0) | |
| { | |
| _connections.Remove(key); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment