有人知道我是否可以在创建C#字典时插入值吗?如果有更高效的方法,我不想每个条目都使用dict.Add(int, "string")
。
Dictionary<int, string>(){(0, "string"),(1,"string2"),(2,"string3")};
有人知道我是否可以在创建C#字典时插入值吗?如果有更高效的方法,我不想每个条目都使用dict.Add(int, "string")
。
Dictionary<int, string>(){(0, "string"),(1,"string2"),(2,"string3")};
这里有一整个页面介绍如何做到这一点:
http://msdn.microsoft.com/en-us/library/bb531208.aspx
例子:
在下面的代码示例中,使用
StudentName
类型的实例初始化了一个Dictionary<TKey, TValue>
:
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}}
};
Dictionary<int, string> dictionary = new Dictionary<int, string> {
{ 0, "string" },
{ 1, "string2" },
{ 2, "string3" } };
你已经接近成功了:
var dict = new Dictionary<int, string>()
{
{0, "string"},
{1, "string2"},
{2, "string3"}
};
您还可以使用Lambda表达式从任何其他IEnumerable对象中插入任何键值对。键和值可以是任何您想要的类型。
Dictionary<int, string> newDictionary =
SomeList.ToDictionary(k => k.ID, v => v.Name);
我发现在.NET中,你可以随处使用IEnumerable对象,这使得操作更加简单。
希望能对你有所帮助!!!
Tad.
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}
};
var dictionary = new Dictionary<int, string>
{
{0, "string"},
{1, "string2"},
{2, "string3"}
};
Dictionary<string, double> D =new Dictionary<string, double>();
D.Add("String", 17.00);
.Add(int, "string")
方法向字典中添加值。很抱歉,这并没有回答问题。 - Kezz这通常不被推荐,但在不确定的危机时刻,您可以使用它
Dictionary<string, object> jsonMock = new Dictionary<string, object>() { { "object a", objA }, { "object b", objB } };
// example of unserializing
ClassForObjectA anotherObjA = null;
if(jsonMock.Contains("object a")) {
anotherObjA = (ClassForObjA)jsonMock["object a"];
}