1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace EasyDevCore.Common
- {
- /// <summary>
- ///
- /// </summary>
- public static class DictionaryHelper
- {
- /// <summary>
- /// Tries to get a value in dictionary.
- /// </summary>
- /// <typeparam name="TKey">The type of the key.</typeparam>
- /// <typeparam name="TValue">The type of the value.</typeparam>
- /// <param name="dict">The dictionary.</param>
- /// <param name="key">The key.</param>
- /// <param name="defaultValue">The default value if key not exists.</param>
- /// <returns></returns>
- public static TValue GetOrDefault<TKey,TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue)
- => dict.ContainsKey(key) ? dict[key] : defaultValue;
- /// <summary>
- /// Gets the or add.
- /// </summary>
- /// <typeparam name="TKey">The type of the key.</typeparam>
- /// <typeparam name="TValue">The type of the value.</typeparam>
- /// <param name="dict">The dictionary.</param>
- /// <param name="key">The key.</param>
- /// <param name="defaultValue">The default value will add and return if key not exits</param>
- /// <returns></returns>
- public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue)
- {
- if (!dict.ContainsKey(key))
- {
- dict[key] = defaultValue;
- }
- return (TValue)dict[key];
- }
- }
- }
|