gpt4 book ai didi

c# - Linq 根据年份和类别选择产品数量

转载 作者:行者123 更新时间:2023-11-30 16:14:34 24 4
gpt4 key购买 nike

我正在尝试绘制如下所示的谷歌条形图 enter image description here

我有对象,它们是

product
{
id,
name,
categoryid
}

category
{
id,
categoryname
}

我试过这样的代码

var grouped = (
from c in allCategories
from p in allProducts

group p by new { year = p.CreateDate.Year} into d

select new { year = d.Key.year, count = d.Count()}).OrderByDescending(g => g.year).Distinct();
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Category Name', '2006', '2011', '2013'],

@foreach (var p in grouped)
{
int productThisYear = grouped.Where(x => x.year <= p.year).Select(x => x.count).Sum();

<text>
['', @productThisYear,@productThisYear,@productThisYear]
</text>
if( counter++ != grouped.Count() - 1){
@Html.Raw(",")
}
}
]);

var options = {
title: 'Product Categories',
hAxis: { title: '' }
};

var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>

但我无法根据此类别名称和年份获取类别名称和产品数量。任何人都可以解释这个问题吗? 在此先感谢您的帮助..

最佳答案

你可以使用join clause像这样

var grouped = (
from c in allCategories
join p in allProducts on c.id equals p.categoryid
group p by new {p.CreateDate.Year, c.categoryname} into g
select new {categoryname=g.Key.categoryname, g.Key.Year, count=g.Count()})
.OrderByDescending(g => g.year);

因此您可以在 foreach 中获取类别名称作为 p.categoryname

关于c# - Linq 根据年份和类别选择产品数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20634456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com