错误解析的返回 JSON 方法
本文关键字:JSON 方法 返回 误解 错误 | 更新日期: 2023-09-27 18:33:55
此方法
var fListItems = db.FListItems.Include(f => f.FList)
.Include(f => f.Item)
.GroupBy(g => new { g.Item.Name, g.FList.Title })
.Select(lg =>
new FListItemsViewModel
{
Title = lg.Key.Title,
ItemStat = new ItemStat
{
Name = lg.Key.Name,
NameCount = lg.Count(),
NameSum = lg.Sum(w => w.Score),
NameAverage = lg.Average(w => w.Score)
}
});
返回此 JSON
[
{
Title: "Animals",
ItemStat: {
Name: "Cat",
NameCount: 2,
NameSum: 8,
NameAverage: 4
}
},
{
Title: "Animals",
ItemStat: {
Name: "Dog",
NameCount: 1,
NameSum: 5,
NameAverage: 5
}
}
]
但我希望它返回这个 JSON:
[
{
Title: "Animals",
ItemStats: [
{
Name: "Cat",
NameCount: 2,
NameSum: 8,
NameAverage: 4
},
{
Name: "Dog",
NameCount: 1,
NameSum: 5,
NameAverage: 5
}
]
}
]
任何人都可以建议如何做到这一点吗?下面是视图模型:
public class FListItemsViewModel
{
public string Title { get; set; }
public ItemStat ItemStat { get; set; }
}
public class ItemStat
{
public string Name { get; set; }
public int NameCount { get; set; }
public int NameSum { get; set; }
public double NameAverage { get; set; }
}
与其在同一子句中GroupBy
Title
和Name
,不如用两个单独的GroupBy
重写我的查询更好吗?
基于拉胡尔回答的进展:
[
{
Title: "Animals",
ItemStat: [
{
Name: "Cat",
NameCount: 2,
NameSum: 8,
NameAverage: 4
},
{
Name: "Cat",
NameCount: 2,
NameSum: 8,
NameAverage: 4
}
]
},
{
Title: "Animals",
ItemStat: [
{
Name: "Dog",
NameCount: 1,
NameSum: 5,
NameAverage: 5
}
]
}
]
为此,
首先,您需要将视图模型更改为::
public class FListItemsViewModel
{
public string Title { get; set; }
public List<ItemStat> ItemStat { get; set; }
}
然后,您可以访问可枚举格式的结果,如下所示:
var fListItems = db.FListItems.Include(f => f.FList)
.Include(f => f.Item)
.GroupBy(g => new { g.Item.Name, g.FList.Title })
.Select(lg =>
new FListItemsViewModel
{
Title = lg.Key.Title,
ItemStat =lg.Select(x=> new ItemStat
{
Name = x.Key.Name,
NameCount = x.Count(),
NameSum = x.Sum(w => w.Score),
NameAverage = x.Average(w => w.Score)
}).ToList()
});
这会产生我想要的输出,所以我想说这就是答案。
除非有人能发现任何不对劲的东西?
var fListItems = db.FListItems.Include(f => f.FList)
.Include(f => f.Item)
.GroupBy(g => g.FaveList.Title)
.Select(lg =>
new FListItemsViewModel
{
Title = lg.Key,
ItemStat = lg.GroupBy(x => x.Item.Name)
.Select(x => new ItemStat
{
Name = x.Key,
NameCount = x.Count(),
NameSum = x.Sum(w => w.Score),
NameAverage = x.Average(w => w.Score)
}).ToList()
});