首页 > 编程语言 >.NET(C#)中new Dictionary(字典)初始化值(initializer默认值)

.NET(C#)中new Dictionary(字典)初始化值(initializer默认值)

时间:2024-02-15 13:33:03浏览次数:34  
标签:初始化 Dictionary C# using new 默认值 字典

 

 .NET(C#)中,当使用new Dictionary<TKey, TValue>()初始化一个字典时,可以通过集合初始化器语法直接为字典添加初始键值对。如需要为字典设置默认值,通常是指为尚未在字典中明确设置的键提供一个默认返回值。Dictionary<TKey, TValue> 类本身不直接支持默认值的概念,但可以通过扩展方法或在尝试访问字典时显式检查键的存在来模拟这种行为。

参考文档:.NET(C#)中new Dictionary(字典)初始化值(initializer默认值)-CJavaPy

1、C# 4.0中指定默认值的方法

在 C# 4.0 中,可以使用集合初始化器语法来初始化 Dictionary<TKey, TValue> 对象。集合初始化器语法可以使用大括号括起来的一系列键值对来初始化字典。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            //C# 4.0
            Dictionary<string, string> myDict =
                new Dictionary<string, string> { { "key1", "value1" },
                    { "key2", "value2" },
                    { "key3", "value3" }
                };
            Console.WriteLine(myDict);
            Dictionary<string, List<string>> myDictList =
                new Dictionary<string, List<string>> { { "key1", new List<string>            () { "value1" } },
                    { "key2", new List<string> () { "value2" } },
                    { "key3", new List<string> () { "value3" } }
                };
            Console.WriteLine(myDictList);
            Dictionary<int, StudentName> students = new Dictionary<int, StudentName>()
               {
                   { 111, new StudentName {FirstName="Sachin", LastName       ="Karnik",     ID=211}},
                   { 112, new StudentName {FirstName="Dina", LastName           ="Salimzianova", ID=317}},
                   { 113, new StudentName {FirstName="Andy", LastName="Ruth",        ID    =198}}
               };
            Console.WriteLine(students);
        }
    }
    class StudentName
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int ID { get; set; }
    }

}

2、C# 6.0中指定默认值的方法

在C# 6.0及之后的版本中,字典初始化可以更加简洁地通过索引器语法进行,这使得在声明并初始化一个Dictionary时代码更加简洁明了。这种方法不仅适用于字典,还适用于其他支持索引器的集合类型。这种初始化方式特别适合在需要预填充一些键值对到字典中的场景。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            Dictionary<int, StudentName> students = new Dictionary<int, StudentName>()
            {
                [111] = new StudentName { FirstName = "Sachin", LastName = "Karnik", ID = 211 },
                [112] = new StudentName { FirstName = "Dina", LastName = "Salimzianova", ID = 317 },
                [113] = new StudentName { FirstName = "Andy", LastName = "Ruth", ID = 198 }
            };
            Console.WriteLine(students);
            //C# 6.0
            Dictionary<string, string> dic =
                new Dictionary<string, string>
                {
                    ["key1"] = "value1",
                    ["key2"] = "value2",
                    ["key3"] = "value3"
                };
            Console.WriteLine(dic);
            Dictionary<string, List<string>> dicList =
                new Dictionary<string, List<string>>
                {
                    ["key1"] = new List<string>() { "value1" },
                    ["key2"] = new List<string>() { "value2" },
                    ["key3"] = new List<string>() { "value3" }
                };
            Console.WriteLine(dicList);
        }
    }
    class StudentName
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int ID { get; set; }
    }

}

参考文档:.NET(C#)中new Dictionary(字典)初始化值(initializer默认值)-CJavaPy

标签:初始化,Dictionary,C#,using,new,默认值,字典
From: https://www.cnblogs.com/tinyblog/p/18016188

相关文章

  • chapter3-排序和查找2
    2.基础查找所谓查找,就是在查找空间中找寻符合要求的解的过程。查找方法有多种,下面简单介绍3种。不同的策略对查找的效率和结果有不同的影响。2.1线性查找从首元素开始,遍历整个序列,直到找到目标元素,则结束算法;或者遍历完序列还没有匹配,则查找失败结束算法。时间复杂度为O(n)。......
  • [Kyana]配置Emacs
    换源;;myself-madeconfig(tool-bar-mode-1)(scroll-bar-mode-1)(setqinhibit-startup-screent);;sourcechangeandconfirm(setqpackage-enable-at-startupnil)(require'package)(setqpackage-archives'(("gnu"."http://mirro......
  • <wicket:child>和<wicket:extend>
    例子:我有一个BasePage.html,只显示页头和页尾:<html><body><spanwicket:id="header">这里显示页头</span><wicket:child/><spanwicket:id="footer">这里显示页尾</span></body></html>————————————————之后编写Child......
  • CF1928E题解
    ModularSequence题目传送门题解发现\(a_i+y\)与\(a_i\bmody\)均不改变\(a_i\)模\(y\)的余数,所以答案序列的每个元素均可表示为\(x\bmody+ky\)的形式,先让\(s\)减去\(n\times(x\bmody)\),再除以\(y\),这样原序列可以被划分为一个从\(\lfloor\dfrac{x}{y}\rflo......
  • 小白也行的:Easy OCR做一款免费的图片转文字
    \text{EasyOCR}支持超过$80$种语言的识别,包括英语、中文(简繁)、阿拉伯文、日文等,并且该库在不断更新中,未来会支持更多的语言。像市面上所有的图片识别都用的是$\text{OCR}$,如微信,百度。个人推荐软件:微信,网站https://web.baimiaoapp.com,该网站识别准确率是真的高,且收费也很人性......
  • tcp ip socket seer agv 连接
    Dotnet.Seer/SeerSocket.csusingSystem.Net;usingSystem.Net.Sockets;usingSystem.Runtime.InteropServices;namespaceSeer.SeerSocket;publicstructSeerMessageHead{publicbytesync;//0x5Apublicbyteversion;//0x01publicushortnumbe......
  • Scanner—使用next方式接收
    packagescanner;importjava.util.Scanner;publicclassnext{publicstaticvoidmain(String[]args){//1.创建一个扫描器对象,用于接收键盘数据Scannerscanner=newScanner(System.in);//输入newScanner(System.in)Alt+回车System.ou......
  • Scanner—使用nextLine方式接收
    packagescanner;importjava.util.Scanner;publicclassnextLine{publicstaticvoidmain(String[]args){//1.创建一个扫描器对象,用于接收键盘数据Scannerscanner=newScanner(System.in);//new.Scanner(System.in)Alt+回车System.......
  • curator操做zookeeper案例
    ApacheCurator客户端的使用curator与客户端的异同zk原生api的不足之处watch注册一次后就会失效不支持递归创建节点会话连接、命名空间和节点创建,递归创建,递归删除packagecom.imooc.curator;importjava.util.List;importorg.apache.curator.RetryPolicy;importorg.......
  • Edu-Dict + English Learning Materials: Mdict
    https://mdict.orghttps://github.com/xiaolai/apple-computer-literacy/blob/main/Install-Mdict-Dictionaries-to-macOS-Dictionary.mdhttps://downloads-direct.freemdict.com/Language_Learning_Videos/英语/https://downloads.freemdict.comhttps://mdx.mdict.orgMdic......