tci*_*and 6 c# linq asp.net json entity-framework
我做了以下linq声明
C#
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);
Run Code Online (Sandbox Code Playgroud)
那回来了
[
{
"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
}
]
Run Code Online (Sandbox Code Playgroud)
但我试图把它变成这种格式
[{
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 }]
},
],
}]
Run Code Online (Sandbox Code Playgroud)
如何修改语句以获得我正在寻找的结果?非linq答案也是可以接受的.
编辑: Region是SubRegion的父级,SubRegion是Country的父级,Count是属于Country的唯一项目数
这是你想要的linq查询(为了便于阅读,我删除了-String
后缀):
var list =
from entity in repository.GetAllEntities()
group entity by entity.Region into regions
let childrenOfRegions =
from region in regions
group region by region.SubRegion into subregions
let countriesOfSubRegions =
from subregion in subregions
group subregion by subregion.Country into countries
select new { Name = countries.Key }
select new { Name = subregions.Key, Children = countriesOfSubRegions }
select new { Name = regions.Key, Children = childrenOfRegions };
Run Code Online (Sandbox Code Playgroud)
Count
在这个查询中没有,因为我真的不明白你在想什么.
我在这里做的是将行分组到区域中,在最后一行中,您可以看到
select new { Name = regions.Key, ... }
我正在返回区域的部分.
要获得子项,您需要将Regions分组为SubRegions(与Regions相同).你一直到国家重复这一点,你已经完成了.
归档时间: |
|
查看次数: |
921 次 |
最近记录: |