using Apewer; using System; using System.Collections.Generic; using System.Text; namespace Apewer.Models { /// [Serializable] public class StringPairs : List> { /// 添加项。返回错误信息。 public string Add(string key, string value) { if (string.IsNullOrEmpty(key)) return "参数 Name 无效。"; // if (string.IsNullOrEmpty(value)) return "参数 Value 无效。"; var kvp = new KeyValuePair(key, value); Add(kvp); return null; } /// 获取所有 Key。 public string[] GetAllKeys() { var keys = new string[Count]; for (var i = 0; i < Count; i++) keys[i] = this[i].Key; return keys; } /// 获取匹配 Key 的所有 Value,不存在 Key 或 Value 时返回空数组。 public string[] GetValues(string key, bool ignoreCase = true, bool withEmpty = true) { if (string.IsNullOrEmpty(key)) return new string[0]; var lowerArg = TextUtility.ToLower(key); var values = new List(); foreach (var item in this) { if (item.Key == key) { if (withEmpty || !string.IsNullOrEmpty(item.Value)) values.Add(item.Value); continue; } if (ignoreCase) { var lowerItem = TextUtility.ToLower(item.Key); if (lowerItem == lowerArg) { if (withEmpty || !string.IsNullOrEmpty(item.Value)) values.Add(item.Value); continue; } } } return values.ToArray(); } /// 获取匹配 Key 的 Value。不存在 Key 时返回 NULL 值。 public string GetValue(string key, bool ignoreCase = true) { if (string.IsNullOrEmpty(key)) return null; // 先精准匹配。 foreach (var item in this) { if (string.IsNullOrEmpty(item.Key)) continue; if (item.Key == key) { if (string.IsNullOrEmpty(item.Value)) continue; return item.Value; } } // 再模糊匹配。 if (ignoreCase) { var lowerArg = TextUtility.ToLower(key); foreach (var item in this) { if (string.IsNullOrEmpty(item.Key)) continue; var lowerKey = TextUtility.ToLower(item.Key); if (lowerKey == lowerArg) { if (string.IsNullOrEmpty(item.Value)) continue; return item.Value; } } } return null; } /// 对 Key 升序排序。 public void Sort() { SortAsc(); } /// 对 Key 升序排序。 public void SortAsc() { base.Sort(new Comparison>((a, b) => a.Key.CompareTo(b.Key))); } /// 对 Key 降序排序。 public void SortDesc() { base.Sort(new Comparison>((b, a) => a.Key.CompareTo(b.Key))); } } }