You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
3.3 KiB

  1. using Apewer;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. namespace Apewer.Models
  6. {
  7. /// <summary></summary>
  8. [Serializable]
  9. public class StringPairs : List<KeyValuePair<string, string>>
  10. {
  11. /// <summary>添加项。返回错误信息。</summary>
  12. public string Add(string key, string value)
  13. {
  14. if (string.IsNullOrEmpty(key)) return "参数 Name 无效。";
  15. if (string.IsNullOrEmpty(value)) return "参数 Value 无效。";
  16. var kvp = new KeyValuePair<string, string>(key, value);
  17. Add(kvp);
  18. return null;
  19. }
  20. /// <summary>获取所有 Key。</summary>
  21. public string[] GetAllKeys()
  22. {
  23. var keys = new string[Count];
  24. for (var i = 0; i < Count; i++) keys[i] = this[i].Key;
  25. return keys;
  26. }
  27. /// <summary>获取匹配 Key 的所有 Value,不存在 Key 或 Value 时返回空数组。</summary>
  28. public string[] GetValues(string key, bool ignoreCase = true, bool withEmpty = true)
  29. {
  30. if (string.IsNullOrEmpty(key)) return new string[0];
  31. var lowerArg = TextUtility.ToLower(key);
  32. var values = new List<string>();
  33. foreach (var item in this)
  34. {
  35. if (item.Key == key)
  36. {
  37. if (withEmpty || !string.IsNullOrEmpty(item.Value)) values.Add(item.Value);
  38. continue;
  39. }
  40. if (ignoreCase)
  41. {
  42. var lowerItem = TextUtility.ToLower(item.Key);
  43. if (lowerItem == lowerArg)
  44. {
  45. if (withEmpty || !string.IsNullOrEmpty(item.Value)) values.Add(item.Value);
  46. continue;
  47. }
  48. }
  49. }
  50. return values.ToArray();
  51. }
  52. /// <summary>获取匹配 Key 的 Value。不存在 Key 时返回 NULL 值。</summary>
  53. public string GetValue(string key, bool ignoreCase = true)
  54. {
  55. if (string.IsNullOrEmpty(key)) return null;
  56. var lowerArg = TextUtility.ToLower(key);
  57. var matched = false;
  58. foreach (var item in this)
  59. {
  60. if (item.Key == key) return item.Value;
  61. if (ignoreCase)
  62. {
  63. var lowerItem = TextUtility.ToLower(item.Key);
  64. if (lowerItem == lowerArg)
  65. {
  66. matched = true;
  67. if (!string.IsNullOrEmpty(item.Value)) return item.Value;
  68. }
  69. }
  70. }
  71. return matched ? "" : null;
  72. }
  73. /// <summary>对 Key 升序排序。</summary>
  74. public void Sort()
  75. {
  76. SortAsc();
  77. }
  78. /// <summary>对 Key 升序排序。</summary>
  79. public void SortAsc()
  80. {
  81. base.Sort(new Comparison<KeyValuePair<string, string>>((a, b) => a.Key.CompareTo(b.Key)));
  82. }
  83. /// <summary>对 Key 降序排序。</summary>
  84. public void SortDesc()
  85. {
  86. base.Sort(new Comparison<KeyValuePair<string, string>>((b, a) => a.Key.CompareTo(b.Key)));
  87. }
  88. }
  89. }