【发布时间】:2010-11-05 14:13:39
【问题描述】:
有谁知道在创建 C# 字典时是否可以将值插入到 C# 字典中?我可以,但不想,做
dict.Add(int, "string") 对于每个项目,如果有更有效的东西,比如:
Dictionary<int, string>(){(0, "string"),(1,"string2"),(2,"string3")};
【问题讨论】:
标签: c# dictionary
有谁知道在创建 C# 字典时是否可以将值插入到 C# 字典中?我可以,但不想,做
dict.Add(int, "string") 对于每个项目,如果有更有效的东西,比如:
Dictionary<int, string>(){(0, "string"),(1,"string2"),(2,"string3")};
【问题讨论】:
标签: c# dictionary
一般不建议这样做,但在不确定的危机时期可以使用
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"];
}
【讨论】:
您知道,从 C# 6 开始,您现在可以按如下方式对其进行初始化
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<string, double> D =new Dictionary<string, double>();
D.Add("String", 17.00);
【讨论】:
.Add(int, "string") 向字典添加值的方法。抱歉,但这并不能回答问题。
这里有一整页关于如何做到这一点:
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}}
};
【讨论】:
您还可以使用 Lambda 表达式插入来自任何其他 IEnumerable 对象的任何键值对。键和值可以是任何你想要的类型。
Dictionary<int, string> newDictionary =
SomeList.ToDictionary(k => k.ID, v => v.Name);
我发现这要简单得多,因为您在 .NET 中的任何地方都使用了 IEnumerable 对象
希望对你有帮助!!!
有点。
【讨论】:
你快到了:
var dict = new Dictionary<int, string>()
{ {0, "string"}, {1,"string2"},{2,"string3"}};
【讨论】:
您可以像这样实例化一个字典并向其中添加项目:
var dictionary = new Dictionary<int, string>
{
{0, "string"},
{1, "string2"},
{2, "string3"}
};
【讨论】:
Dictionary<int, string> dictionary = new Dictionary<int, string> {
{ 0, "string" },
{ 1, "string2" },
{ 2, "string3" } };
【讨论】: