DictionaryHelper.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace EasyDevCore.Common
  7. {
  8. /// <summary>
  9. ///
  10. /// </summary>
  11. public static class DictionaryHelper
  12. {
  13. /// <summary>
  14. /// Tries to get a value in dictionary.
  15. /// </summary>
  16. /// <typeparam name="TKey">The type of the key.</typeparam>
  17. /// <typeparam name="TValue">The type of the value.</typeparam>
  18. /// <param name="dict">The dictionary.</param>
  19. /// <param name="key">The key.</param>
  20. /// <param name="defaultValue">The default value if key not exists.</param>
  21. /// <returns></returns>
  22. public static TValue GetOrDefault<TKey,TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue)
  23. => dict.ContainsKey(key) ? dict[key] : defaultValue;
  24. /// <summary>
  25. /// Gets the or add.
  26. /// </summary>
  27. /// <typeparam name="TKey">The type of the key.</typeparam>
  28. /// <typeparam name="TValue">The type of the value.</typeparam>
  29. /// <param name="dict">The dictionary.</param>
  30. /// <param name="key">The key.</param>
  31. /// <param name="defaultValue">The default value will add and return if key not exits</param>
  32. /// <returns></returns>
  33. public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue defaultValue)
  34. {
  35. if (!dict.ContainsKey(key))
  36. {
  37. dict[key] = defaultValue;
  38. }
  39. return (TValue)dict[key];
  40. }
  41. }
  42. }