gpt4 book ai didi

c# - 如何在 C# 中向字典添加多个值?

转载 作者:可可西里 更新时间:2023-11-01 02:58:33 24 4
gpt4 key购买 nike

如果我不想多次调用“.Add()”,那么向字典添加多个值的最佳方法是什么。

编辑:印心后要填!字典中已经有一些值了!

所以代替

    myDictionary.Add("a", "b");
myDictionary.Add("f", "v");
myDictionary.Add("s", "d");
myDictionary.Add("r", "m");
...

我想做这样的事情

 myDictionary.Add(["a","b"], ["f","v"],["s","d"]);

有办法吗?

最佳答案

您可以为此使用花括号,尽管这仅适用于初始化:

var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"},
{"s", "d"},
{"r", "m"}
};

这称为“集合初始化”并且适用于任何 ICollection<T> (有关字典,请参阅 link 或有关任何其他集合类型的 link)。事实上,它适用于任何实现 IEnumerable 的对象类型。并包含 Add方法:

class Foo : IEnumerable
{
public void Add<T1, T2, T3>(T1 t1, T2 t2, T3 t3) { }
// ...
}

Foo foo = new Foo
{
{1, 2, 3},
{2, 3, 4}
};

基本上这只是调用 Add 的语法糖- 方法反复。初始化后有几种方法可以做到这一点,其中之一是调用 Add - 手动方法:

var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"}
};

var anotherDictionary = new Dictionary<string, string>
{
{"s", "d"},
{"r", "m"}
};

// Merge anotherDictionary into myDictionary, which may throw
// (as usually) on duplicate keys
foreach (var keyValuePair in anotherDictionary)
{
myDictionary.Add(keyValuePair.Key, keyValuePair.Value);
}

或者作为扩展方法:

static class DictionaryExtensions
{
public static void Add<TKey, TValue>(this IDictionary<TKey, TValue> target, IDictionary<TKey, TValue> source)
{
if (source == null) throw new ArgumentNullException("source");
if (target == null) throw new ArgumentNullException("target");

foreach (var keyValuePair in source)
{
target.Add(keyValuePair.Key, keyValuePair.Value);
}
}
}

var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"}
};

myDictionary.Add(new Dictionary<string, string>
{
{"s", "d"},
{"r", "m"}
});

关于c# - 如何在 C# 中向字典添加多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23565974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com