I am trying to add an extension for a Dictionary who takes key-value a key and a Dictionary, as follows, but I receive error 'Cannot implicitly convert type bool to string':
public static string GetParameterValue(
this Dictionary<string, Dictionary<string, string>> src, string section, string key, out string value)
{
value = null;
if (src.TryGetValue(section, out Dictionary<string, string> sectionValue))
{
return sectionValue.TryGetValue(key, out value); //error
}
return string.Empty;
}
I have multiple sections (imagine categories) and each section has a huge list of parameters and their values; section One has a list of key/value pairs, section Two the same etc. I am trying to have a Dictionary which is of the form
Dictionary<string, Dictionary<string, string>> Sections = new Dictionary<string, Dictionary<string, string>>();
which I populate like
Sections["Italian"].Add("Good morning", "Buon giorno");
and I want to have an extension so that I can do
string myWord = Sections.GetParameterValue("Italian", "Good morning")
so that myWord is "Buon giorno".
Maybe could you help?
CodePudding user response:
try this
Dictionary<string, Dictionary<string, string>> Sections = new Dictionary<string, Dictionary<string, string> >();
Sections.AddParameterValue("Italian","Good afternoon", "Buon afternoon");
Sections.AddParameterValue("Italian","Good morning", "Buon giorno");
string myWord = Sections.GetParameterValue("Italian", "Good morning");
public static class Extensions
{
public static string GetParameterValue(
this Dictionary<string, Dictionary<string, string>> src, string key1, string key2)
{
if (src.TryGetValue(key1, out var sectionValue))
if (sectionValue.TryGetValue(key2, out var result)) return result;
return string.Empty;
}
public static void AddParameterValue(
this Dictionary<string, Dictionary<string, string>> src, string section, string key, string value)
{
if (!src.TryGetValue(section, out _)) src[section] = new Dictionary<string, string>();
if (src[section].TryGetValue(key, out _)) src[section][key] = value;
else src[section].Add(key, value);
}
}
