Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq GroupBy to switch dimensions

Tags:

c#

linq

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

like image 698
user1044169 Avatar asked Apr 26 '13 19:04

user1044169


2 Answers

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
}
like image 191
Jon Skeet Avatar answered Nov 08 '22 16:11

Jon Skeet


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());
like image 25
p.s.w.g Avatar answered Nov 08 '22 18:11

p.s.w.g