1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ICSharpCode.NRefactory6.CSharp
{
static class IDictionaryExtensions
{
// Copied from ConcurrentDictionary since IDictionary doesn't have this useful method
public static V GetOrAdd<K, V>(this IDictionary<K, V> dictionary, K key, Func<K, V> function)
{
V value;
if (!dictionary.TryGetValue(key, out value))
{
value = function(key);
dictionary.Add(key, value);
}
return value;
}
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
TValue value;
if (dictionary.TryGetValue(key, out value))
{
return value;
}
return default(TValue);
}
public static bool DictionaryEquals<K, V>(this IDictionary<K, V> left, IDictionary<K, V> right, IEqualityComparer<KeyValuePair<K, V>> comparer = null)
{
comparer = comparer ?? EqualityComparer<KeyValuePair<K, V>>.Default;
// two dictionaries should have same number of entries
if (left.Count != right.Count)
{
return false;
}
// check two dictionaries have same key/value pairs
return left.All(pair => comparer.Equals(pair));
}
public static void MultiAdd<TKey, TValue, TCollection>(this IDictionary<TKey, TCollection> dictionary, TKey key, TValue value)
where TCollection : ICollection<TValue>, new()
{
TCollection collection;
if (!dictionary.TryGetValue(key, out collection))
{
collection = new TCollection();
dictionary.Add(key, collection);
}
collection.Add(value);
}
public static void MultiRemove<TKey, TValue, TCollection>(this IDictionary<TKey, TCollection> dictionary, TKey key, TValue value)
where TCollection : ICollection<TValue>
{
TCollection collection;
if (dictionary.TryGetValue(key, out collection))
{
collection.Remove(value);
if (collection.Count == 0)
{
dictionary.Remove(key);
}
}
}
public static void MultiAddRange<TKey, TValue, TCollection>(this IDictionary<TKey, TCollection> dictionary, TKey key, IEnumerable<TValue> values)
where TCollection : ICollection<TValue>, new()
{
TCollection collection;
if (!dictionary.TryGetValue(key, out collection))
{
collection = new TCollection();
dictionary.Add(key, collection);
}
foreach (var val in values)
collection.Add (val);
}
}
}
|