我有连接映射类。我需要通过索引访问_connections
并实施RemoveAt(indx)
方法。
类别:
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 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);
}
}
}
}
public IEnumerable<string> GetConnections(T key)
{
HashSet<string> connections;
if (_connections.TryGetValue(key, out connections))
{
return connections;
}
return Enumerable.Empty<string>();
}
}
示例:
_connections.RemoveAt(0);
_connections[0].Value = _value,
_connections[0].Key = _key;
如何修改类来实现这个目标?
答案 0 :(得分:1)
字典不保留其元素的任何顺序,因此无法知道要删除哪一个。您只能使用Remove(TKey key)
。
或者您可以使用OrderedDictionary
Represents a collection of key/value pairs that are accessible by the key or index.
RemoveAt
已经实施
OrderedDictionary.RemoveAt
答案 1 :(得分:1)
字典不维护顺序,因此在给定索引处没有一致的项目概念。考虑从KeyedCollection<TKey, TValue>
继承:
using System.Collections.ObjectModel;
public class ConnectionMapping<T>
{
private class Mapping
{
public T Key;
public HashSet<string> Items;
}
private class ConnectionsCollection : KeyedCollection<T, Mapping>
{
protected override T GetKeyForItem(Mapping item)
{
return item.Key;
}
}
private readonly ConnectionsCollection _connections = new ConnectionsCollection();
/// Implementation of various collection methods, Add, RemoveAt, etc.
public void RemoveAt(int index)
{
lock(_connections)
{
_connections.RemoveAt(index);
}
}
}
您可能希望在ConnectionsCollection
上添加一些辅助方法,以进行类似字典的访问(例如TryGetValue)。您目前的锁定是不够的。您还需要锁定GetConnections
。不要从那里返回实际的集合,返回connections
。