forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDictionaryExtensions.cs
More file actions
60 lines (50 loc) · 1.75 KB
/
DictionaryExtensions.cs
File metadata and controls
60 lines (50 loc) · 1.75 KB
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
using System;
using System.Collections.Generic;
using ServiceStack;
public static class DictionaryExtensions
{
public static TValue GetValueOrDefault<TValue, TKey>(this Dictionary<TKey, TValue> dictionary, TKey key)
{
return dictionary.ContainsKey(key) ? dictionary[key] : default(TValue);
}
public static void ForEach<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, Action<TKey, TValue> onEachFn)
{
foreach (var entry in dictionary)
{
onEachFn(entry.Key, entry.Value);
}
}
public static bool UnorderedEquivalentTo<K, V>(this IDictionary<K, V> thisMap, IDictionary<K, V> otherMap)
{
if (thisMap == null || otherMap == null) return thisMap == otherMap;
if (thisMap.Count != otherMap.Count) return false;
foreach (var entry in thisMap)
{
V otherValue;
if (!otherMap.TryGetValue(entry.Key, out otherValue)) return false;
if (!Equals(entry.Value, otherValue)) return false;
}
return true;
}
public static List<T> ConvertAll<T, K, V>(IDictionary<K, V> map, Func<K, V, T> createFn)
{
var list = new List<T>();
map.Each((kvp) => list.Add(createFn(kvp.Key, kvp.Value)));
return list;
}
public static V GetOrAdd<K, V>(this Dictionary<K, V> map, K key, Func<K, V> createFn)
{
//simulate ConcurrentDictionary.GetOrAdd
lock (map)
{
V val;
if (!map.TryGetValue(key, out val))
map[key] = val = createFn(key);
return val;
}
}
public static KeyValuePair<TKey, TValue> PairWith<TKey, TValue>(this TKey key, TValue value)
{
return new KeyValuePair<TKey, TValue>(key, value);
}
}