gpt4 book ai didi

c# - 如何为复杂词典增加值(value)?

转载 作者:行者123 更新时间:2023-12-04 16:28:12 24 4
gpt4 key购买 nike

据我所知,为字典添加值的方法如下。

    Dictionary<string, string> myDict = new Dictionary<string, string>();

myDict.Add("a", "1");

如果我将“myDictDict”声明为下面的样式。
IDictionary<string, Dictionary<string, string>> myDictDict = new Dictionary<string, Dictionary<string, string>>();

myDictDict .Add("hello", "tom","cat"); ?// How to add value here.

谢谢你。

最佳答案

正确的做法是这样的:

// myDictDict is Dictionary<string, Dictionary<string, string>>
Dictionary<string, string> myDict;
string key = "hello";
if (!myDictDict.TryGetValue(key, out myDict)) {
myDict = new Dictionary<string, string>();
myDictDict.Add(key, myDict);
}
myDict.Add("tom", "cat");

这将提取与键对应的字典(在您的示例中为 hello)或在必要时创建它,然后将键/值对添加到该字典中。您甚至可以将其提取到扩展方法中。
static class Extensions {
public static void AddToNestedDictionary<TKey, TNestedDictionary, TNestedKey, TNestedValue>(
this IDictionary<TKey, TNestedDictionary> dictionary,
TKey key,
TNestedKey nestedKey,
TNestedValue nestedValue
) where TNestedDictionary : IDictionary<TNestedKey, TNestedValue> {
dictionary.AddToNestedDictionary(
key,
nestedKey,
nestedValue,
() => (TNestedDictionary)(IDictionary<TNestedKey, TNestedValue>)
new Dictionary<TNestedKey, TNestedValue>());
}

public static void AddToNestedDictionary<TKey, TNestedDictionary, TNestedKey, TNestedValue>(
this IDictionary<TKey, TNestedDictionary> dictionary,
TKey key,
TNestedKey nestedKey,
TNestedValue nestedValue,
Func<TNestedDictionary> provider
) where TNestedDictionary : IDictionary<TNestedKey, TNestedValue> {
TNestedDictionary nested;
if (!dictionary.TryGetValue(key, out nested)) {
nested = provider();
dictionary.Add(key, nested);
}
nested.Add(nestedKey, nestedValue);
}
}

我遗漏了防范 null输入以保持想法清晰。
用法:
myDictDict.AddToNestedDictionary(
"hello",
"tom",
"cat",
() => new Dictionary<string, string>()
);

或者
myDictDict.AddToNesteDictionary("hello", "tom", "cat");

关于c# - 如何为复杂词典增加值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1967821/

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