利用C# Map集合实现数据的快速检索

   2024-09-30 6180
核心提示:在C#中,Map集合通常是指DictionaryTKey, TValueusing System;using System.Collections.Generic;class Program{static void Mai

在C#中,Map集合通常是指Dictionary<TKey, TValue>

using System;using System.Collections.Generic;class Program{    static void Main()    {        // 创建一个字典,键为字符串,值为整数        Dictionary<string, int> map = new Dictionary<string, int>();        // 向字典中添加数据        map.Add("apple", 1);        map.Add("banana", 2);        map.Add("orange", 3);        // 检索并输出"apple"对应的值        if (map.TryGetValue("apple", out int value))        {            Console.WriteLine($"The value of 'apple' is: {value}");        }        else        {            Console.WriteLine("Key not found.");        }        // 更新"apple"的值        map["apple"] = 4;        // 删除"banana"        map.Remove("banana");        // 遍历字典并输出所有键值对        foreach (var item in map)        {            Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");        }    }}

在这个示例中,我们首先创建了一个Dictionary<string, int>类型的变量map。然后,我们向字典中添加了三个键值对。接下来,我们使用TryGetValue方法检索并输出"apple"对应的值。之后,我们更新"apple"的值,并删除"banana"。最后,我们遍历字典并输出所有键值对。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号