如何将值插入到实例化的C#字典中? [英] How to insert values into C# Dictionary on instantiation?

查看:643
本文介绍了如何将值插入到实例化的C#字典中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道有没有办法,当我创建它可以插入值到C#字典?我可以,但不想,如果有一些更有效的如下所示,为每个项目做
dict.Add(int,string) / p>

 字典< int,string>(){(0,string),(1,string2),(2 STRING3)}; 


解决方案

有关如何在这里完成的整个页面: / p>

http:// msdn .microsoft.com / en-us / library / bb531208.aspx



示例:


在下面的代码示例中, Dictionary< TKey,TValue>
,初始化类型为 StudentName的实例




  var 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}}
};


Does anyone know if there is a way I can insert values into a C# Dictionary when I create it? I can, but don't want to, do dict.Add(int, "string") for each item if there is something more efficient like:

Dictionary<int, string>(){(0, "string"),(1,"string2"),(2,"string3")};

解决方案

There's whole page about how to do that here:

http://msdn.microsoft.com/en-us/library/bb531208.aspx

Example:

In the following code example, a Dictionary<TKey, TValue> is initialized with instances of type StudentName:

var 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}}
};

这篇关于如何将值插入到实例化的C#字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆