DictionaryExtensions.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Text;
  4. namespace YBEE.EQM.Core;
  5. /// <summary>
  6. /// 字典扩展
  7. /// </summary>
  8. public static class DictionaryExtensions
  9. {
  10. /// <summary>
  11. /// 将一个字典转化为 QueryString
  12. /// </summary>
  13. /// <param name="dict"></param>
  14. /// <param name="urlEncode"></param>
  15. /// <returns></returns>
  16. public static string ToQueryString(this Dictionary<string, string> dict, bool urlEncode = true)
  17. {
  18. return string.Join("&", dict.Select(p => $"{(urlEncode ? p.Key?.UrlEncode() : "")}={(urlEncode ? p.Value?.UrlEncode() : "")}"));
  19. }
  20. /// <summary>
  21. /// 将一个字符串 URL 编码
  22. /// </summary>
  23. /// <param name="str"></param>
  24. /// <returns></returns>
  25. public static string UrlEncode(this string str)
  26. {
  27. if (string.IsNullOrEmpty(str))
  28. {
  29. return "";
  30. }
  31. return System.Web.HttpUtility.UrlEncode(str, Encoding.UTF8);
  32. }
  33. /// <summary>
  34. /// 移除空值项
  35. /// </summary>
  36. /// <param name="dict"></param>
  37. public static void RemoveEmptyValueItems(this Dictionary<string, string> dict)
  38. {
  39. dict.Where(item => string.IsNullOrEmpty(item.Value)).Select(item => item.Key).ToList().ForEach(key =>
  40. {
  41. dict.Remove(key);
  42. });
  43. }
  44. }