我想创建这样的扩展方法:
public static void AddToList<T,U>(this Dictionary<T,List<U>> dictionary, T key, U value)
{
// If the list exist, add to the list.
// Else Create the list and add the item.
}
这是我到目前为止所尝试的:
public static void AddToList<T,U>(this Dictionary<T,List<U>> dictionary, T key, U value)
{
if (!dictionary.ContainsKey(key) || dictionary[key] == null)
{
dictionary[key] = new List<U>();
}
dictionary[key].Add(value);
}
如何使用此方法处理线程安全?
如果需要线程安全,则可以改用ConcurrentDictionary
。
var dictionary = new ConcurrentDictionary<T, List<U>>();
List<U> values = dictionary.GetOrAdd(key, _ => new List<U>());
一些补充说明:
TryGetValue
而不是GetOrAdd
以避免创建不必要的List<U>
。List<U>
的线程安全问题。您仍然需要处理各个列表上的操作。我将开始使用ConcurrentDictionary<TKey, TValue>
,它负责在字典中添加不存在的列表的线程安全性。
[请注意,您始终将项目添加到列表中,而不是在检查项目是否已在列表中。如果需要,那是保证线程安全的又一个额外步骤。
public static void AddToList<T, U>(
this ConcurrentDictionary<T, List<U>> dictionary,
T key,
U value
) {
var list = dictionary.GetOrAdd(key, k => new List<U>());
list.Add(value);
}