wabbajack/Wabbajack.Common/Extensions/DictionaryExt.cs

59 lines
1.7 KiB
C#
Raw Normal View History

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)
where K : notnull
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)
where K : notnull
{
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)
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)
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);
}
}
}