【问题标题】:Grouping Date by month in MVC Chart在 MVC 图表中按月分组日期
【发布时间】:2017-06-06 08:29:57
【问题描述】:

我想统计一个月内的新用户数。然而,这是我收到的输出。我如何将重复的月份分组为“一月”、“十一月”。非常感谢您的帮助。

Image of output

public ActionResult UserPerMonth()
{

    var _con = new DBEntities();
    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();
    var results = (from c in _con.Users select c);
    results.ToList().ForEach(rs => yValue.Add(rs.id.ToString().Count()));
    results.ToList().ForEach(rs => xValue.Add(rs.date.Value.ToString("MMM-yyyy")));

    var chart = new Chart(width: 300, height: 200)
                .AddTitle("Users per month")
                .AddLegend()
                .AddSeries(
                chartType: "Column",
                xValue: xValue,
                yValues: yValue)
                .GetBytes("png");
     return File(chart, "image/png");
 }

【问题讨论】:

    标签: c# asp.net-mvc linq asp.net-mvc-5


    【解决方案1】:

    可能有更简洁的方法,但这对我有用。为您的图表数据添加一个类,例如

    public class ChartData
    {
        public string Month { get; set; }
        public int Count { get; set; }
    }
    

    然后您可以使用带有 groupby 和 count 的 linq 查询来获取数据并将其放入 ChartData 类型,然后将这些值移动到相关轴:

    public ActionResult UserPerMonth()
    {
    
        var _con = new DBEntities();
        ArrayList xValue = new ArrayList();
        ArrayList yValue = new ArrayList();
    
        var results = (from c in _con.Users select c);
    
        var axis = results.GroupBy(r => r.date.Value.ToString("MMM-yyyy"))
                .Select(r => new ChartData
                {
                    Month = r.Key,
                    Count = r.Count()
                }).ToList();
    
        foreach (var item in axis)
        {
            xValue.Add(item.Month);
            yValue.Add(item.Count);
        }
    
    
        var chart = new Chart(width: 300, height: 200)
            .AddTitle("Users per month")
            .AddLegend()
            .AddSeries(
                chartType: "Column",
                xValue: xValue,
                yValues: yValue)
            .GetBytes("png");
        return File(chart, "image/png");
    }
    

    【讨论】:

    • 感谢您的帮助,我认为这部分的拼写错误 Month = n.Key, Count = n.Count(),但是代码不显示图表@James
    • 抱歉,是的,已经修正了错字 - 你可以试试。如果没有请设置断点,看看axis的值是多少?
    猜你喜欢
    • 1970-01-01
    • 2013-04-05
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 2012-02-03
    • 1970-01-01
    相关资源
    最近更新 更多