2019-11-06 01:39:18 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
|
|
|
|
namespace Wabbajack
|
|
|
|
|
{
|
|
|
|
|
public static class DictionaryExt
|
|
|
|
|
{
|
|
|
|
|
public static V TryCreate<K, V>(this IDictionary<K, V> dict, K key)
|
2020-04-03 23:23:13 +00:00
|
|
|
|
where K : notnull
|
2019-11-06 01:39:18 +00:00
|
|
|
|
where V : new()
|
|
|
|
|
{
|
|
|
|
|
return dict.TryCreate(key, () => new V());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static V TryCreate<K, V>(this IDictionary<K, V> dict, K key, Func<V> create)
|
2020-04-03 23:23:13 +00:00
|
|
|
|
where K : notnull
|
2019-11-06 01:39:18 +00:00
|
|
|
|
{
|
|
|
|
|
if (dict.TryGetValue(key, out var val)) return val;
|
|
|
|
|
var ret = create();
|
|
|
|
|
dict[key] = ret;
|
|
|
|
|
return ret;
|
|
|
|
|
}
|
2020-04-02 00:43:49 +00:00
|
|
|
|
|
2020-04-09 21:05:07 +00:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// Adds the given values to the dictionary. If a key already exists, it will throw an exception
|
|
|
|
|
/// </summary>
|
2020-04-02 00:43:49 +00:00
|
|
|
|
public static void Add<K, V>(this IDictionary<K, V> dict, IEnumerable<KeyValuePair<K, V>> vals)
|
2020-04-03 23:23:13 +00:00
|
|
|
|
where K : notnull
|
2020-04-02 00:43:49 +00:00
|
|
|
|
{
|
|
|
|
|
foreach (var val in vals)
|
|
|
|
|
{
|
|
|
|
|
dict.Add(val);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-04-09 21:05:07 +00:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// Adds the given values to the dictionary. If a key already exists, it will be replaced
|
|
|
|
|
/// </summary>
|
2020-04-02 00:43:49 +00:00
|
|
|
|
public static void Set<K, V>(this IDictionary<K, V> dict, IEnumerable<KeyValuePair<K, V>> vals)
|
2020-04-03 23:23:13 +00:00
|
|
|
|
where K : notnull
|
2020-04-02 00:43:49 +00:00
|
|
|
|
{
|
|
|
|
|
foreach (var val in vals)
|
|
|
|
|
{
|
|
|
|
|
dict[val.Key] = val.Value;
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-04-09 21:05:07 +00:00
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Clears the dictionary and adds the given values
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static void SetTo<K, V>(this IDictionary<K, V> dict, IEnumerable<KeyValuePair<K, V>> vals)
|
|
|
|
|
where K : notnull
|
|
|
|
|
{
|
|
|
|
|
dict.Clear();
|
|
|
|
|
dict.Set(vals);
|
|
|
|
|
}
|
2019-11-06 01:39:18 +00:00
|
|
|
|
}
|
|
|
|
|
}
|