阅读量:2
在C#中,SortedDictionary是一个有序字典,它根据键的顺序存储和排序元素。要删除SortedDictionary中的元素,您可以使用Remove()方法。以下是一个示例:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
SortedDictionary<int, string> mySortedDictionary = new SortedDictionary<int, string>();
// 添加元素到SortedDictionary
mySortedDictionary.Add(3, "three");
mySortedDictionary.Add(1, "one");
mySortedDictionary.Add(2, "two");
Console.WriteLine("Original SortedDictionary:");
foreach (KeyValuePair<int, string> item in mySortedDictionary)
{
Console.WriteLine("{0}: {1}", item.Key, item.Value);
}
// 删除SortedDictionary中的元素
int keyToRemove = 2;
if (mySortedDictionary.ContainsKey(keyToRemove))
{
mySortedDictionary.Remove(keyToRemove);
Console.WriteLine($"Element with key {keyToRemove} removed.");
}
else
{
Console.WriteLine($"Element with key {keyToRemove} not found.");
}
Console.WriteLine("\nSortedDictionary after removal:");
foreach (KeyValuePair<int, string> item in mySortedDictionary)
{
Console.WriteLine("{0}: {1}", item.Key, item.Value);
}
}
}
在这个示例中,我们首先创建了一个SortedDictionary,并添加了一些元素。然后,我们使用Remove()方法删除了键为2的元素。最后,我们遍历SortedDictionary并输出其内容。
以上就是关于“c# sorteddictionary怎样删除”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm