Anyone know the correct linq query to get this result?
The LINQ is fairly straight forward and closely follows @Konstantin's answer...
var dict = new Dictionary<string, List<string>>
{
{"A1",new List<string> { "B1", "B2", "B3" }},
{"A2",new List<string> { "B1" }},
{"A3",new List<string> { "B1", "B2"}},
};
IEnumerable<IGrouping<string,string>> inverted =
from kvp in dict
from child in kvp.Value
group kvp.Key by child;
The IGrouping<string,string>
has a string Key
property corresponding to the unique child from the dict
. The IGrouping<string,string>
is IEnumerable<string>
which in this case is the parents requested. In other words, this IGrouping is a lot like the original Dictionary<string,List<string>>
we started with. Interestingly, a select clause is unnecessary because the language spec permits a query to end with a group-by.
Additionally, if a Dictionary is desired instead of an IGrouping, the ToDictionary extension makes this simple:
Dictionary<string,List<string>> invertedDict =
inverted.ToDictionary(i => i.Key, i => i.ToList());