title: C# + EntityFramework: Convert multiple group by query to nested JSON
body: <p>I made the following linq statement</p>
  
  <p><strong>C#</strong></p>
  
  <pre><code>var list = from row in repository.GetAllEntities()
                         group row by new { row.RegionString, row.SubRegionString, row.CountryString } into g
                         select new { g.Key.RegionString, g.Key.SubRegionString, g.Key.CountryString, Count = g.Count() };
  
  return Json(list, JsonRequestBehavior.AllowGet);
  </code></pre>
  
  <p>That returns </p>
  
  <pre><code>[
    {
      "RegionString":"Americas",
      "SubRegionString":"",
      "CountryString":"",
      "Count":2
    },
    {
      "RegionString":"Americas",
      "SubRegionString":"NorthAmerica",
      "CountryString":"Canada",
      "Count":5
    },
    {
      "RegionString":"Americas",
      "SubRegionString":"NorthAmerica",
      "CountryString":"US",
      "Count":3
    },
    {
      "RegionString":"Americas",
      "SubRegionString":"SouthAmerica",
      "CountryString":"Chile",
      "Count":3
    },
    {
      "RegionString":"EMEA",
      "SubRegionString":"AsiaPacific",
      "CountryString":"Australia",
      "Count":2
    },
    {
      "RegionString":"EMEA",
      "SubRegionString":"AsiaPacific",
      "CountryString":"Japan",
      "Count":1
    },
    {
      "RegionString":"EMEA",
      "SubRegionString":"SouthernEurope",
      "CountryString":"Turkey",
      "Count":1
    },
    {
      "RegionString":"EMEA",
      "SubRegionString":"WesternEurope",
      "CountryString":"",
      "Count":1
    }
  ]
  </code></pre>
  
  <p>But I am trying to make it into this format</p>
  
  <pre><code>[{
      name: "Americas",
      children: [
       {
           name: "NorthAmerica",
           children: [{ "name": "Canada", "count": 5 },
                      { "name": "US", "count": 3 }]
  
       },
       {
           name: "SouthAmerica",
           children: [{ "name": "Chile", "count": 1 }]
       },
      ],
  },
  {
      name: "EMA",
      children: [
       {
           name: "AsiaPacific",
           children: [{ "name": "Australia", "count": 2 },
                      { "name": "Japan", "count": 1 }]
  
       },
       {
           name: "SouthernEurope",
           children: [{ "name": "Turkey", "count": 1 }]
       },
      ],
  }]
  </code></pre>
  
  <p>How could I modify the statement to get the result I'm looking for? Non linq answers are acceptable too.</p>
  
  <p><strong>EDIT:</strong> Region is the parent of SubRegion, SubRegion is the parent of Country and Count is the unique number of items that belongs to Country</p>