2021-11-07 13:51:45 +01:00
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
2021-02-10 14:53:56 +01:00
|
|
|
|
|
|
|
|
namespace zero.Core.Extensions
|
|
|
|
|
{
|
|
|
|
|
public static class DictionaryExtensions
|
|
|
|
|
{
|
|
|
|
|
public static bool TryGetValue<T>(this Dictionary<string, object> model, string key, out T value)
|
|
|
|
|
{
|
|
|
|
|
if (!model.TryGetValue(key, out object valueObj) || !(valueObj is T))
|
|
|
|
|
{
|
|
|
|
|
value = default;
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
value = (T)valueObj;
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static T GetValueOrDefault<T>(this Dictionary<string, object> model, string key)
|
|
|
|
|
{
|
2021-03-02 16:16:29 +01:00
|
|
|
object value = model.GetValueOrDefault(key);
|
2021-02-10 14:53:56 +01:00
|
|
|
return value == default || !(value is T) ? default : (T)value;
|
|
|
|
|
}
|
2021-11-07 13:51:45 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
public static Dictionary<TKey, TElement> ToDistinctDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
|
|
|
|
|
{
|
|
|
|
|
Dictionary<TKey, TElement> result = new();
|
|
|
|
|
|
|
|
|
|
foreach (TSource sourceElement in source)
|
|
|
|
|
{
|
|
|
|
|
result.TryAdd(keySelector(sourceElement), elementSelector(sourceElement));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
}
|
2021-02-10 14:53:56 +01:00
|
|
|
}
|
|
|
|
|
}
|