Double group into Dictionary<int, Dictionary<string, List<Model>>>()

Viewed 73

I hope this can be resolved by LINQ without any additional operations.

For input I have a list of models:

public class Model 
{
  public int A { get; set; }
  public string B { get; set; }
  public int C { get; set; }
}

On the result I should have

Dictionary<int, Dictionary<string, List<Model>>>();

I have tried next example:

 var r = (from t in list
                    group t by new {t.A, t.B}
                    into grp
                    select new
                    {
                        grp.Key.A,
                        grp.Key.B,
                        Q = grp
                    }).ToList();

But it gives me not that I expected, is there any way how to solve this ?

1 Answers

Given that you have a list of type List, you can use:

var list = new List<Model>();

var lookup = list.GroupBy(model => new { A = model.A, B = model.B }).GroupBy(grp => grp.Key.A).ToDictionary(grp => grp.Key, grp => grp.ToDictionary(subgrp => subgrp.Key.B, subgrp => subgrp.ToList()));

You will see that the variable lookup has the type you are looking for.

How it works:

By the first GroupBy, you are creating an IGrouping that has an anonymous key type that has the members int A and string B. This is because:

Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.

This was an answer to a question I asked a few years ago, you can examine it and @xanatos's excellent answer if you like.

Related