我正在尝试绘制一个像
下面的谷歌条形图我有对象,
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>
但我无法根据此类别名称和年份获得类别名称和产品计数。任何机构都可以解释问题? 在此先感谢您的帮助..
答案 0 :(得分:3)
你可以像这样使用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