Given
Dictionary<string, List<string>> myDict = new Dictionary<string, List<string>>()
{
"Apples", new List<string>() { "Green", "Red" },
"Grapefruits", new List<string>() { "Sweet", "Tart" },
}
I wish to create a mapping from the child to the parent, e.g.
“Green” => “Apples”
In my particular use case, the child strings will be globally unique (e.g. no Green Grapefruits to worry about), so the mapping could be to a Dictionary<string,string>.
It’s fairly straightforward to accomplish by iterating myDict conventionally.
Dictionary<string, string> map = new Dictionary<string,string>();
foreach (KeyValuePair<string, List<string>> kvp in myDict)
{
foreach (string name in kvp.Value)
{
map.Add(name, kvp.Key);
}
}
Can this be done with Linq?
There is a very similar question about just flattening the same data structure
Flatten a C# Dictionary of Lists with Linq
However that does not maintain the relationship to the dictionary key.
I reviewed a nice visual tutorial on SelectMany (the approach used in the related question) but see no way to relate the key.
Sounds like you want:
Note that the second argument to
SelectManyhere looks a little odd here, because the original key becomes the value in the final dictionary, and vice versa.