温馨提示×

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

c#
小樊
123
2024-09-04 15:46:27
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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>实例。请根据您的需求选择合适的方法。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:如何在C#中初始化一维数组

0