C# 中的 SortedDictionary.Clear() 方法

2024 年 8 月 29 日 | 阅读 2 分钟

在本文中,我们将讨论 C# 中的 SortedDictionary.Clear() 方法。SortedDictionary 是一种通用集合,用于以排序格式存储键值对,其中排序基于键。SortedDictionary 定义在 System.Collection.Generic 命名空间中。它是动态的,这意味着 SortedDictionary 的大小会根据需要增长。

什么是 SortedDictionary?

SortedDictionary 要求键是唯一的。不允许使用重复键。在 SortedDictionary 中,键是不可变的,也不能为 null。如果值类型是引用类型,SortedDictionary 允许值为 null。它在未排序数据上提供最快的插入和删除操作。SortedDictionary 只能存储相同类型的键值对。SortedDictionary 的容量是指 SortedDictionary 可以容纳的键值对的数量。

SortedDictionary.Clear() 方法会从 SortedDictionary 中删除所有键值对。

语法

它具有以下语法:

下面的程序将用于描述 SortedDictionary.Clear() 方法。

示例 1

让我们以一个例子来实现 C# 中的 SortedDictionary.clear() 方法。

输出

The total number of key/value pairs in dict is: 8
The total pairs after the clear() method:
The total number of key/value pairs in dict is: 0

示例 2

让我们以另一个例子来实现 C# 中的 SortedDictionary.clear() 方法。

输出

The total number of key/value pairs in dict is: 9
The total pairs after the clear() method:
The total number of key/value pairs in dict is : 0