编程语言
首页 > 编程语言> > C#-Linq根据年份和类别选择产品计数

C#-Linq根据年份和类别选择产品计数

作者:互联网

我正在尝试绘制如下的Google条形图

我有一些东西

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

标签:google-visualization,linq,c
来源: https://codeday.me/bug/20191122/2059088.html