英文:
C# dictionary initialization
问题
以下是您要翻译的内容:
"Is here any ways to initialize dictionary key-value pair with same values without copying code? For example like this:
Dictionary<string, IReadonlyCollection
{
["someKey"] = new[] { <value from key "someKey">, "anotherValue", ect... }
}
Update:
Dictionary<string,string[]> _dict = new(GetPairs());
KeyValuePair<string, string[]>[] GetPairs()
{
GetPair("key", "value", "value2"),
}
KeyValuePair<string, string[]> GetPair(string key, params string[] values)
{
var values2 = new[] { key };
return new KeyValuePair<string,string[]>(
key,
values2.Concat(names ?? Array.Empty<string>()));
}"
英文:
Is here any ways to initialize dictionary key-value pair with same values without copying code?
For example like this:
Dictionary<string, IReadonlyCollection<string>> dic = new()
{
["someKey"] = new[] { <value from key "someKey">, "anotherValue", ect... }
}
Update:
Dictionary<string,string[]> _dict = new(GetPairs());
KeyValuePair<string, string[]>[] GetPairs()
{
GetPair("key", "value", "value2"),
}
KeyValuePair<string, string[]> GetPair(string key, params string[] values)
{
var values2 = new[] { key };
return new KeyValuePair<string,string[]>(
key,
values2.Concat(names ?? Array.Empty<string>()));
}
答案1
得分: 3
不可以,因为在其集合初始化器内部,dic
在语法上尚未初始化。
这个:
var dic = new Dictionary<string, object>
{
["foo"] = "Foo",
["bar"] = dic["foo"],
};
会产生以下错误:
CS0841 无法在声明之前使用局部变量 'dic'
另一种方法是事先指定内容并引用它:
const string foo = "Foo";
var dic = new Dictionary<string, object>
{
["foo"] = foo,
["bar"] = foo,
};
或者去掉初始化语法:
var dic = new Dictionary<string, object>();
dic["foo"] = dic["bar"] = "Foo";
英文:
No, because syntactically the dic
isn't initialized yet within its collection initializer.
This:
var dic = new Dictionary<string, object>
{
["foo"] = "Foo",
["bar"] = dic["foo"],
};
Yields:
> CS0841 Cannot use local variable 'dic' before it is declared
An alternative would be to specify the contents on beforehand, and reference that:
const string foo = "Foo";
var dic = new Dictionary<string, object>
{
["foo"] = foo,
["bar"] = foo,
};
Or get rid of the initializer syntax:
var dic = new Dictionary<string, object>();
dic["foo"] = dic["bar"] = "Foo";
答案2
得分: 1
以下是您要翻译的内容:
您可以定义一个具有重载Add方法的专用字典,如下所示:
public class MyDictionary : Dictionary<string, string[]>
{
public void Add(params string[] values)
{
if (values.Length < 1)
throw new ArgumentException("至少需要一个字符串作为参数");
base.Add(values[0], values);
}
}
然后,您可以这样初始化它:
var dict = new MyDictionary
{
{"SomeKey", "other value", "another value" },
{"Some other key", "some other value", "again" }
};
foreach (var item in dict)
{
Console.WriteLine($"[{item.Key}, [{string.Join(", ", item.Value)}]]");
}
// 输出:
// [SomeKey, [SomeKey, other value, another value]]
// [Some other key, [Some other key, some other value, again]]
您可以根据需要调整添加方法。
其他解决方案:
如果您不想创建一个专用的字典,您可以使用Linq的ToDictionary
方法来初始化字典。首先,您初始化一个string[]
的集合,然后从中创建字典。
以下是示例代码:
IReadOnlyDictionary<string, string[]> dictionary
= new List<string[]>
{
new [] {"KeyA", "ValueA1", "ValueA2" },
new [] {"KeyB", "ValueB1", "ValueB2", "ValueB3"}
}.ToDictionary(t => t[0], t => t);
希望这有帮助!
英文:
You can define a specialized dictionary with an overload Add method as:
public class MyDictionary : Dictionary<string, string[]>
{
public void Add(params string[] values)
{
if (values.Length < 1)
throw new ArgumentException("At least one string as argument");
base.Add(values[0], values);
}
}
and then you can initialize it as:
var dict = new MyDictionary
{
{"SomeKey", "other value", "another value" },
{"Some other key", "some other value", "again" }
};
foreach (var item in dict)
{
Console.WriteLine($"[{item.Key}, [{string.Join(", ",item.Value)}]]");
}
// Output:
// [SomeKey, [SomeKey, other value, another value]]
// [Some other key, [Some other key, some other value, again]]
You may adapt the add method as you need
Other solution:
If you don't want to create e specialized dictionary, you can use Linq's ToDictionary
method to initialize the dictionary.
You first initialize a collection of string[]
and then crete the dictionary from it.
Here a sample code:
IReadOnlyDictionary<string, string[]> dictionary
= new List<string[]>
{
new [] {"KeyA", "ValueA1", "ValueA2" },
new [] {"KeyB", "ValueB1", "ValueB2", "ValueB3"}
}.ToDictionary(t=>t[0], t=>t);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论