如何在C#中初始化Map集合

   2024-09-30 6650
核心提示:在C#中,您可以使用DictionaryTKey, TValue来表示Map集合方法1:使用Collection Initializer语法(需要C# 3.0及更高版本)using

在C#中,您可以使用Dictionary<TKey, TValue>来表示Map集合

方法1:使用Collection Initializer语法(需要C# 3.0及更高版本)

using System;using System.Collections.Generic;class Program{    static void Main()    {        var map = new Dictionary<string, int>        {            {"one", 1},            {"two", 2},            {"three", 3}        };        foreach (var item in map)        {            Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");        }    }}

方法2:使用Add()方法逐个添加元素

using System;using System.Collections.Generic;class Program{    static void Main()    {        var map = new Dictionary<string, int>();        map.Add("one", 1);        map.Add("two", 2);        map.Add("three", 3);        foreach (var item in map)        {            Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");        }    }}

这两种方法都会创建一个包含三个键值对的Dictionary<string, int>实例。请根据您的需求选择合适的方法。

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

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