C#字典初始化

huangapple go评论54阅读模式
英文:

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> 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>()));

}"

英文:

Is here any ways to initialize dictionary key-value pair with same values without copying code?
For example like this:

Dictionary&lt;string, IReadonlyCollection&lt;string&gt;&gt; dic = new() 
{
    [&quot;someKey&quot;] = new[] { &lt;value from key &quot;someKey&quot;&gt;, &quot;anotherValue&quot;, ect... }
}

Update:

Dictionary&lt;string,string[]&gt; _dict = new(GetPairs());

KeyValuePair&lt;string, string[]&gt;[] GetPairs()
{ 
 GetPair(&quot;key&quot;, &quot;value&quot;, &quot;value2&quot;),
}

KeyValuePair&lt;string, string[]&gt; GetPair(string key, params string[] values) 
{
    var values2 = new[] { key }; 

    return new KeyValuePair&lt;string,string[]&gt;(
      key, 
      values2.Concat(names ?? Array.Empty&lt;string&gt;()));
}

答案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&lt;string, object&gt;
{
    [&quot;foo&quot;] = &quot;Foo&quot;,
    [&quot;bar&quot;] = dic[&quot;foo&quot;],
};

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 = &quot;Foo&quot;;
var dic = new Dictionary&lt;string, object&gt;
{
    [&quot;foo&quot;] = foo,
    [&quot;bar&quot;] = foo,
};

Or get rid of the initializer syntax:

var dic = new Dictionary&lt;string, object&gt;();

dic[&quot;foo&quot;] = dic[&quot;bar&quot;] = &quot;Foo&quot;;

答案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&lt;string, string[]&gt;
{
    public void Add(params string[] values)
    {
        if (values.Length &lt; 1)
            throw new ArgumentException(&quot;At least one string as argument&quot;);

        base.Add(values[0], values);
    }
}

and then you can initialize it as:

var dict = new MyDictionary
{
    {&quot;SomeKey&quot;, &quot;other value&quot;, &quot;another value&quot; },
    {&quot;Some other key&quot;, &quot;some other value&quot;, &quot;again&quot; }
};

foreach (var item in dict)
{
    Console.WriteLine($&quot;[{item.Key}, [{string.Join(&quot;, &quot;,item.Value)}]]&quot;);
}
// 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&lt;string, string[]&gt; dictionary
        = new List&lt;string[]&gt; 
        {
            new [] {&quot;KeyA&quot;, &quot;ValueA1&quot;, &quot;ValueA2&quot; },
            new [] {&quot;KeyB&quot;, &quot;ValueB1&quot;, &quot;ValueB2&quot;, &quot;ValueB3&quot;}
        }.ToDictionary(t=&gt;t[0], t=&gt;t);

huangapple
  • 本文由 发表于 2023年5月17日 21:39:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272773.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定