C# Dictionary<TKey, TValue>使用

发布于:2024-03-06 ⋅ 阅读:(79) ⋅ 点赞:(0)

在C#中,Dictionary<TKey, TValue>是一个键值对集合,其中键和值都是字符串类型。

以下是关于如何向字典的示例:

添加数据到 Dictionary<string, string>:

// 创建一个新的 Dictionary
Dictionary<string, string> dictionary = new Dictionary<string, string>();

// 向字典中添加键值对
dictionary.Add("Key1", "Value1"); // 添加第一个键值对
dictionary.Add("Key2", "Value2"); // 添加第二个键值对

// 或者使用索引器直接赋值(如果确保键不存在)
dictionary["Key3"] = "Value3";

// 示例输出:
// dictionary 的内容现在是:{ Key1: Value1, Key2: Value2, Key3: Value3 }

移除 Dictionary<string, string>中数据:

// 假设我们有一个已填充数据的字典
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("Key1", "Value1");
dictionary.Add("Key2", "Value2");

// 移除指定键的键值对
string keyToRemove = "Key1";
if (dictionary.ContainsKey(keyToRemove))
{
    dictionary.Remove(keyToRemove);
}

// 示例输出:
// 在移除 "Key1" 后,字典的内容为:{ Key2: Value2 }

清空 Dictionary<string, string>:

// 使用 Clear 方法清空字典中的所有键值对
dictionary.Clear();

// 清空后,字典将不包含任何元素。

 

Dictionary<TKey, TValue>使用:Dictionary<string, string>、Dictionary<int, string>等等方法同上;

其他方法:

C# Dictionary中GetEnumerator()方法_c# getenumerator-CSDN博客

wpf “Key”属性只能用于“IDictionary”中包含的元素。_key属性只能用于idic-CSDN博客

 


网站公告


今日签到

点亮在社区的每一天
去签到