我有一个清单:
List<DataBanerModel> banerData = new List<DataBanerModel>();
banerData.Add(new DataBanerModel { Shop = 1, Cartoon = 1, Box = 1 });
banerData.Add(new DataBanerModel { Shop = 1, Cartoon = 1, Box = 2 });
banerData.Add(new DataBanerModel { Shop = 1, Cartoon = 1, Box = 3 });
banerData.Add(new DataBanerModel { Shop = 1, Cartoon = 2, Box = 1 });
banerData.Add(new DataBanerModel { Shop = 1, Cartoon = 2, Box = 2 });
banerData.Add(new DataBanerModel { Shop = 1, Cartoon = 2, Box = 3 });
banerData.Add(new DataBanerModel { Shop = 1, Cartoon = 3, Box = 1 });
banerData.Add(new DataBanerModel { Shop = 2, Cartoon = 1, Box = 1 });
banerData.Add(new DataBanerModel { Shop = 2, Cartoon = 1, Box = 2 });
banerData.Add(new DataBanerModel { Shop = 2, Cartoon = 1, Box = 3 });
banerData.Add(new DataBanerModel { Shop = 3, Cartoon = 1, Box = 1 });
banerData.Add(new DataBanerModel { Shop = 3, Cartoon = 1, Box = 2 });
banerData.Add(new DataBanerModel { Shop = 3, Cartoon = 1, Box = 3 });
banerData.Add(new DataBanerModel { Shop = 3, Cartoon = 2, Box = 1 });
banerData.Add(new DataBanerModel { Shop = 3, Cartoon = 2, Box = 2 });
我必须计算在
Box
中将有多少Cartoon
es,在Cartoon
中将有多少Shop
s,所以结果应该是这样的:Shop: 1, Cartoons: 3, Boxes: 3
Shop: 1, Cartoons: 3, Boxes: 3
Shop: 1, Cartoons: 3, Boxes: 1
Shop: 2, Cartoons: 1, Boxes: 3
Shop: 3, Cartoons: 2, Boxes: 3
Shop: 3, Cartoons: 2, Boxes: 2
到目前为止,我写道:
var step4 = banerData.GroupBy(x => x.Shop)
.Select(s => new
{
Shops = s.Key,
Cartoons = s.GroupBy(y => y.Cartoon)
.Select(k => new
{
k.Key,
Boxes = k.GroupBy(z => z.Box)
.Select(p => p.Key).ToList()
}).ToList()
}).ToList();
它工作正常,但我不知道如何展平这棵树。
最佳答案
您可以使用:
var grouped = banerData
.GroupBy(d => d.Shop)
.Select(g => new
{
Shop = g.Key,
Cartoon = g.Select(i => i.Cartoon).Distinct().Count(),
Box = g
.GroupBy(i => i.Cartoon)
.Select(gr => gr.Select(i => i.Box).Distinct().Count())
.ToArray()
}).SelectMany(i => i.Box.Select(ii => new { i.Shop, i.Cartoon, Box = ii }))
.ToList();