Files
Prowlarr/src/NzbDrone.Common/Extensions/DictionaryExtensions.cs
T
ta264 b5b43b8b3f Changed: Align GetValueOrDefault extension with netcore3.0 version
- netcore3.0 implements the extenion on IReadOnlyDictionary.
 - Dictionary implements both IReadonlyDictionary and IDictionary and
   so defining the extenion on both interfaces creates an ambiguous
   reference
 - IDictionary doesn't inherit from IReadOnlyDictionary

Either we have to add 'using NzbDrone.Common.Extenions;'
separately to resolve the ambiguity or we have to standardaize on only
having the extension on IReadOnlyDictionary.
2019-10-15 20:22:50 -04:00

49 lines
1.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
namespace NzbDrone.Common.Extensions
{
public static class DictionaryExtensions
{
#if !NETCOREAPP3_0
public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue = default(TValue))
{
TValue value;
return dictionary.TryGetValue(key, out value) ? value : defaultValue;
}
#endif
public static Dictionary<T1, T2> Merge<T1, T2>(this Dictionary<T1, T2> first, Dictionary<T1, T2> second)
{
if (first == null) throw new ArgumentNullException("first");
if (second == null) throw new ArgumentNullException("second");
var merged = new Dictionary<T1, T2>();
first.ToList().ForEach(kv => merged[kv.Key] = kv.Value);
second.ToList().ForEach(kv => merged[kv.Key] = kv.Value);
return merged;
}
public static void Add<TKey, TValue>(this ICollection<KeyValuePair<TKey, TValue>> collection, TKey key, TValue value)
{
collection.Add(new KeyValuePair<TKey, TValue>(key, value));
}
public static IDictionary<TNewKey, TNewValue> SelectDictionary<TKey, TValue, TNewKey, TNewValue>(this IDictionary<TKey, TValue> dictionary,
Func<KeyValuePair<TKey, TValue>, ValueTuple<TNewKey, TNewValue>> selection)
{
return dictionary.Select(selection).ToDictionary(t => t.Item1, t => t.Item2);
}
public static IDictionary<TNewKey, TNewValue> SelectDictionary<TKey, TValue, TNewKey, TNewValue>(
this IDictionary<TKey, TValue> dictionary,
Func<KeyValuePair<TKey, TValue>, TNewKey> keySelector,
Func<KeyValuePair<TKey, TValue>, TNewValue> valueSelector)
{
return dictionary.SelectDictionary(p => { return (keySelector(p), valueSelector(p)); });
}
}
}