c# 高级编程 10章218页 【集合】【有序列表SortedList<TKey, TValue>】

156 阅读1分钟

SortedList<TKey, TValue>

  • 基于来给元素排序
  • 构造函数
    • 无参构造
    • 重载,可以传入IComparer<TKey>
    • 重载,可以指定容量

SortedList<TKey, TValue>添加元素

  • Add():如果键已存在就抛出ArgumentException
  • 索引器[]: 如果键已存在,就用新值替换旧值

SortedList<TKey, TValue>遍历元素

  • foreach遍历:枚举器返回的是KeyValuePair<TKey, TValue>
  • Values属性:IList<TValue>类型
  • Keys属性: IList<TKey>类型

SortedList<TKey, TValue>访问一个元素

  • 索引器[]:如果键不存在,就抛出KeyNotFoundException
    • 建议搭配ContainsKey()方法来使用
  • TryGetValue()方法:如果键不存在,就返回false

示例

    class Program
    {
        static void Main()
        {
            var books = new SortedList<string, string>();
            books.Add("Professional WPF Programming", "978–0–470–04180–2");
            books.Add("Professional ASP.NET MVC 5", "978–1–118-79475–3");

            books["Beginning C# 6 Programming"] = "978-1-119-09668-9";
            books["Professional C# 6 and .NET Core 1.0"] = "978-1-119-09660-3";

            foreach (KeyValuePair<string, string> book in books)
            {
                Console.WriteLine($"{book.Key}, {book.Value}");
            }

            foreach (string isbn in books.Values)
            {
                Console.WriteLine(isbn);
            }

            foreach (string title in books.Keys)
            {
                Console.WriteLine(title);
            }

            {
                string title = "Professional C# 8";
                if (!books.TryGetValue(title, out string isbn))
                {
                    Console.WriteLine($"{title} not found");
                }
            }
        }
    }

输出:

Beginning C# 6 Programming, 978-1-119-09668-9
Professional ASP.NET MVC 5, 9781118-794753
Professional C# 6 and .NET Core 1.0, 978-1-119-09660-3
Professional WPF Programming, 9780470041802
978-1-119-09668-9
9781118-794753
978-1-119-09660-3
9780470041802
Beginning C# 6 Programming
Professional ASP.NET MVC 5
Professional C# 6 and .NET Core 1.0
Professional WPF Programming
Professional C# 8 not found