I have this structure:
var data1 = new Dictionary<int, List<string>>
{
{ 1, new List<string> { "A", "B", "C" } },
{ 2, new List<string> { "B", "C" } }
};
and I need to transform it to this structure:
var data2 = new Dictionary<string, List<int>>
{
{ "A", new List<int> { 1 } },
{ "B", new List<int> { 1, 2 } },
{ "C", new List<int> { 1, 2 } }
};
How can I use Linq to do that? Do I use GroupBy?
Thanks
Do you definitely need it to be a Dictionary<string, List<int>>
or just something similar? I'd use SelectMany
to flatten, and then ToLookup
:
var data2 = data1.SelectMany(pair => pair.Value, (p, v) => new { p.Key, Value = v })
.ToLookup(x => x.Value, x => x.Key);
Then you can still use it as if it were a dictionary:
foreach (var x in data2["B"])
{
Console.WriteLine(x); // Prints 1 then 2
}
You can do this:
var data2 =
(from p in data1
from v in p.Value
group p by v)
.ToDictionary(g => g.Key, g => g.Select(x => x.Key).ToList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With