C# 创建一个以数组为值的字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9960312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a dictionary with arrays as values
提问by Jodll
I'm trying to initialize a dictionary with string elements as keys and int[] elements as values, as follows:
我正在尝试使用字符串元素作为键和 int[] 元素作为值来初始化字典,如下所示:
System.Collections.Generic.Dictionary<string,int[]> myDictionary;
myDictionary = new Dictionary<string,int[]>{{"length",{1,1}},{"width",{1,1}}};
But the debugger keeps saying: "Unexpected symbol '{'".
但是调试器一直说:“意外的符号'{'”。
Could you tell me what's wrong with the above code?
你能告诉我上面的代码有什么问题吗?
Thank you!
谢谢!
采纳答案by kasavbere
I am not sure for c# but the following works in Java for example:
我不确定 c# 但以下在 Java 中有效,例如:
instead of
代替
{1,1}
try
尝试
new int[]{1,1}
or
或者
new[]{1,1}
回答by Star
System.Collections.Generic.Dictionary<string,int[]> myDictionary;
myDictionary = new Dictionary<string, int[]> { { "length", new int[] { 1, 1 } }, { "width", new int[] { 1, 1 } } };
回答by Nicholas
You will need to specify that it's an array that you are inserting in to your Dictionary:
您需要指定它是要插入到字典中的数组:
System.Collections.Generic.Dictionary<string, int[]> myDictionary;
myDictionary = new Dictionary<string, int[]> {{"length", new int[]{1,2}},{ "width",new int[]{3,4}}};
回答by Dan Ricker
Below are two examples that work. The second example only works inside a method. The first example will work inside a method or outside a method in a class.
下面是两个有效的例子。第二个示例仅适用于方法内部。第一个示例将在方法内部或类中的方法外部工作。
The initial code was missing the () for the new Dictionary() statement which is probably what gave the "{" unexepcted symbol error. The "new Int[]" is also required
初始代码缺少 new Dictionary() 语句的 (),这可能是导致“{”意外符号错误的原因。还需要“new Int[]”
class SomeClass
{
Dictionary<string, int[]> myDictionary = new Dictionary<string, int[]>()
{
{"length", new int[] {1,1} },
{"width", new int[] {1,1} },
};
public void SomeMethod()
{
Dictionary<string, int[]> myDictionary2;
myDictionary2 = new Dictionary<string, int[]>()
{
{"length", new int[] {1,1} },
{"width", new int[] {1,1} },
};
}
}
回答by Sandeep
In addition to all good answers you can also try this.
除了所有好的答案外,您还可以试试这个。
Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();
If possible prefer List<> over arrays as resizing is difficult in Arrays. You can not delete an element from an array. But an element can be deleted from List.
如果可能的话,更喜欢 List<> 而不是数组,因为在数组中调整大小很困难。不能从数组中删除元素。但是可以从 List 中删除元素。

