Tutorialsteacher

关注我们

文章
  • C#
  • C# 面向对象编程
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • 控制反转 (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • 正则表达式
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • C# - 入门
  • C# - 版本历史
  • C# - 第一个程序
  • C# - 关键词
  • C# - 类和对象
  • C# - 命名空间
  • C# - 变量
  • C# - 隐式类型变量
  • C# - 数据类型
  • 数字
  • 字符串
  • DateTime
  • 结构体
  • 枚举
  • StringBuilder
  • 匿名类型
  • 动态类型
  • 可空类型
  • C# - 值类型和引用类型
  • C# - 接口
  • C# - 运算符
  • C# - if else 语句
  • C# - 三元运算符 ?
  • C# - Switch 语句
  • C# - For 循环
  • C# - While 循环
  • C# - Do-while 循环
  • C# - 分部类
  • C# - Static 关键字
  • C# - 数组
  • 多维数组
  • 交错数组
  • C# - 索引器
  • C# - 泛型
  • 泛型约束
  • C# - 集合
  • ArrayList
  • List
  • SortedList
  • Dictionary
  • Hashtable
  • Stack
  • Queue
  • C# - Tuple
  • C# - ValueTuple
  • C# - 内置异常
  • 异常处理
  • throw 关键字
  • 自定义异常
  • C# - 委托
  • Func 委托
  • Action 委托
  • Predicate 委托
  • 匿名方法
  • C# - 事件
  • C# - 协变
  • C# - 扩展方法
  • C# - 流 I/O
  • C# - File 类
  • C# - FileInfo 类
  • C# - 对象初始化器
  • OOP - 概述
  • 面向对象编程
  • 抽象
  • 封装
  • 关联与组合
  • 继承
  • 多态
  • 方法重写
  • 方法隐藏
  • C# - SOLID 原则
  • 单一职责原则
  • 开闭原则
  • 里氏替换原则
  • 接口隔离原则
  • 依赖倒置原则
  • 设计模式
  • 单例模式
  • 抽象工厂模式
  • 工厂方法模式
Entity Framework Extensions - 提升 EF Core 9
  批量插入
  批量删除
  批量更新
  批量合并

C# - SortedList<TKey, TValue>

SortedList<TKey, TValue> 和 SortedList 是集合类,可以存储键值对,这些键值对根据关联的 IComparer 实现按键排序。例如,如果键是基元类型,则按键的升序排序。

C# 支持泛型和非泛型 SortedList。建议使用泛型 SortedList<TKey, TValue>,因为它比非泛型 SortedList 性能更快,更不容易出错。

SortedList 特性

  • SortedList<TKey, TValue> 是一个按键排序的键值对数组。
  • 元素添加后立即排序。基元类型键按升序排序,对象键根据 IComparer<T> 排序。
  • 属于 System.Collection.Generic 命名空间。
  • 键必须是唯一的,且不能为 null。
  • 值可以为 null 或重复。
  • 可以通过在索引器 mySortedList[key] 中传入关联的键来访问值。
  • 包含 KeyValuePair<TKey, TValue> 类型的元素。
  • 它比 SortedDictionary<TKey,TValue> 使用更少的内存。
  • 一旦排序,它在数据检索方面更快,而 SortedDictionary<TKey, TValue> 在插入和删除键值对方面更快。

创建 SortedList

以下示例演示如何创建泛型 SortedList<TKey, TValue> 并向其中添加键值对。

示例:创建 SortedList 并添加元素
//SortedList of int keys, string values 
SortedList<int, string> numberNames = new SortedList<int, string>();
numberNames.Add(3, "Three");
numberNames.Add(1, "One");
numberNames.Add(2, "Two");
numberNames.Add(4, null);
numberNames.Add(10, "Ten");
numberNames.Add(5, "Five");

//The following will throw exceptions
//numberNames.Add("Three", 3); //Compile-time error: key must be int type
//numberNames.Add(1, "One"); //Run-time exception: duplicate key
//numberNames.Add(null, "Five");//Run-time exception: key cannot be null
尝试一下

在上面的示例中,通过指定要存储的键和值的类型来创建泛型 SortedList<TKey, TValue> 对象。SortedList<int, string> 将存储 int 类型的键和 string 类型的值。

Add() 方法用于在 SortedList 中添加单个键值对。键不能为 null 或重复。如果发现,它将抛出运行时异常。如果类型可为空,则值可以重复和为 null。

使用集合初始化器语法在实例化时初始化一个包含多个键值对的 SortedList,如下所示。

//Creating a SortedList of string keys, string values 
//using collection-initializer syntax
SortedList<string,string> cities = new SortedList<string,string>()
                                    {
                                        {"London", "UK"},
                                        {"New York", "USA"},
                                        { "Mumbai", "India"},
                                        {"Johannesburg", "South Africa"}
                                    };

SortedList 在添加键值对后会立即按键的升序重新排列键值对。以下示例使用 foreach 循环显示所有键和值。

示例:SortedList 元素的默认排序顺序
SortedList<int,string> numberNames = new SortedList<int,string>()
                                    {
                                        {3, "Three"},
                                        {5, "Five"},
                                        {1, "One"}
                                    };

Console.WriteLine("---Initial key-values--");

foreach(KeyValuePair<int, string> kvp in numberNames)
    Console.WriteLine("key: {0}, value: {1}", kvp.Key , kvp.Value );

numberNames.Add(6, "Six");
numberNames.Add(2, "Two");
numberNames.Add(4, "Four");

Console.WriteLine("---After adding new key-values--");

foreach(var kvp in numberNames)
    Console.WriteLine("key: {0}, value: {1}", kvp.Key , kvp.Value );
尝试一下
输出
---初始键值对--
键: 1, 值: One
键: 3, 值: Three
键: 5, 值: Five
---添加新键值对后--
键: 1, 值: One
键: 2, 值: Two
键: 3, 值: Three
键: 4, 值: Four
键: 5, 值: Five
键: 6, 值: Six

访问 SortedList

在索引器 sortedList[key] 中指定一个键,以获取或设置 SortedList 中的值。

示例:访问 SortedList 值
SortedList<int,string> numberNames = new SortedList<int,string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"}
                                    };

Console.WriteLine(numberNames[1]); //output: One
Console.WriteLine(numberNames[2]); //output: Two
Console.WriteLine(numberNames[3]); //output: Three
//Console.WriteLine(numberNames[10]); //run-time KeyNotFoundException

numberNames[2] = "TWO"; //updates value
numberNames[4] = "Four"; //adds a new key-value if a key does not exists
尝试一下

上面,numberNames[10] 将抛出 KeyNotFoundException,因为指定的键 10 不存在于 sortedlist 中。为了防止此异常,请使用 ContainsKey() 或 TryGetValue() 方法,如下所示。

示例:ContainsKey() 和 TryGetValue()
SortedList<int, string> numberNames = new SortedList<int,string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"}
                                    };
if(numberNames.ContainsKey(4)){
    numberNames[4] = "four";
}

int result;
if(numberNames.TryGetValue(4, out result))
    Console.WriteLine("Key: {0}, Value: {1}", 4, result);
尝试一下
输出
键:4, 值: Four

如果要使用 for 循环遍历 SortedList,请使用 Keys 和 Values 属性。

示例:使用 For 循环遍历 SortedList
SortedList<int, string> numberNames = new SortedList<int,string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"}
                                    };
for (int i = 0; i < numberNames.Count; i++)
{
    Console.WriteLine("key: {0}, value: {1}", numberNames.Keys[i], numberNames.Values[i]);
}
尝试一下
输出
键: 1, 值: One
键: 2, 值: Two
键: 3, 值: Three

从 SortedList 中移除元素

使用 Remove(key) 和 RemoveAt(index) 方法从 SortedList 中移除键值对。

示例:移除元素
SortedList<int,string> numberNames = new SortedList<int,string>()
                                    {
                                        {3, "Three"},
                                        {1, "One"},
                                        {2, "Two"},
                                        {5, "Five"},
                                        {4, "Four"}
                                    };
    
numberNames.Remove(1);//removes key 1 pair
numberNames.Remove(10);//removes key 1 pair, no error if not exists

numberNames.RemoveAt(0);//removes key-value pair from index 0 
//numberNames.RemoveAt(10);//run-time exception: ArgumentOutOfRangeException

foreach(var kvp in numberNames)
	Console.WriteLine("key: {0}, value: {1}", kvp.Key , kvp.Value );
尝试一下
输出
键: 3, 值: Three
键: 4, 值: Four
键: 5, 值: Five

SortedList 类层次结构

下图说明了 SortedList 的层次结构。

SortedList Hierarchy

在 docs.microsoft.com 上了解更多关于 SortedList 方法和属性的信息

TUTORIALSTEACHER.COM

TutorialsTeacher.com 是您权威的技术教程来源,旨在通过循序渐进的方法,指导您掌握各种网络和其他技术。

我们的内容旨在帮助所有水平的学习者轻松快速地学习技术。访问此平台即表示您已阅读并同意遵守我们的使用条款和隐私政策,这些条款旨在保障您的体验和隐私权利。

[email protected]

关于我们使用条款隐私政策
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) 版权所有。