【问题标题】:Compute running total in c# from linq query在 C# 中从 linq 查询计算运行总计
【发布时间】:2012-09-07 22:57:47
【问题描述】:

我花了好几天学习 linq 并从我的控制器在 mvc 中生成 json 结果。然而,我现在遇到了一个问题,我希望滚动 Y 轴数据的总和(累积总和)值以生成年初至今的折线图。

我目前生成简单月度数据的代码如下:

//Generic Json For Graphs
public JsonResult GetJSONYTD(int kpiID)
{
    var ViewData = 
        (from kpidata in departmentrepo.GetGraphData(kpiID)
         select new DepartmentOverviewDetailsViewModel.GraphJSONViewModel
         {
             XData = kpidata.Year.Year1 + "-" 
                     + kpidata.Month.Real_Month_Int + "-01",
             YData = kpidata.Value
         });

    var ChartData = ViewData.Select(
                        x => new object[] { x.XData, x.YData }).ToArray();

    return Json(ChartData, JsonRequestBehavior.AllowGet);
}

上面产生了以下数组:

[
 ["2011-10-01",0],
 ["2011-11-01",22],
 ["2011-12-01",22],
 ["2012-1-01",14],
 ["2012-2-01",14.4],
 ["2012-3-01",17.5],
 ["2012-4-01",20.3],
 ["2012-5-01",23.5],
 ["2012-6-01",24.5],
 ["2012-7-01",26.5]
]

我想输出:

[
 ["2011-10-01",0],
 ["2011-11-01",22],
 ["2011-12-01",44],
 ["2012-1-01",38],
 ["2012-2-01",52.4],
 etc
]

有什么帮助吗?

【问题讨论】:

  • 38 应该是 58 吗? (然后 52.4 变成 72.4?)
  • 很可能我是在早上的一个愚蠢的时间打出来的:p

标签: c# asp.net-mvc arrays json linq


【解决方案1】:

将您的代码更改为:

//图的通用Json

public JsonResult GetJSONYTD(int kpiID)
{
    var graphData = departmentrepo.GetGraphData(kpiID);
    var ViewData = (from kpidata in graphData

                    select new DepartmentOverviewDetailsViewModel.GraphJSONViewModel
                    {
                        XData = kpidata.Year.Year1 + "-" + kpidata.Month.Real_Month_Int + "-01",
                        YData = graphData.Where(x=>x.Date<=kpidata.Date).Sum(x=>x.Value)
                    });

    var ChartData = ViewData.Select(x => new object[] { x.XData, x.YData }).ToArray();

    return Json(ChartData, JsonRequestBehavior.AllowGet);
}

以上代码将在 YData 中存储数据小于或等于当前日期的所有数据点的总和。

【讨论】:

  • 插入上述内容时出现错误:Error 1 'ES_Business_Intelligence.Models.KPIData' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'ES_Business_Intelligence.Models.KPIData' could be found (are you missing a using directive or an assembly reference?) C:\Data\Common\Dropbox\Work\Databases\Web_Applications\ES_Business_Intelligence\ES_Business_Intelligence\Controllers\DepartmentOverviewController.cs 145 41 ES_Business_Intelligence
  • 更改了一小部分代码以查看 where 子句 YData = graphData.Where(x =&gt; x.ID &lt;= kpidata.ID).Sum(x =&gt; x.Value) 中的 ID 号,除此之外......完美:)
  • 最终输出:[["2011-10-01",0],["2011-11-01",22],["2011-12-01",44],["2012-1-01",58],["2012-2-01",72.4],["2012-3-01",89.9],["2012-4-01",110.2],["2012-5-01",133.7],["2012-6-01",158.2],["2012-7-01",184.7]]
【解决方案2】:

您可以使用 Aggregate 内联执行此操作:

    var rollingSum = ViewData.Aggregate(
        // start with a list of a single model with value 0 (this avoids func having to deal with the empty list case
        seed: new[] { new DepartmentOverviewDetailsViewModel.GraphJSONViewModel { XData = string.Empty, YData = 0.0 } }.ToList(),
        // the aggregation function adds to the list a new tuple with the current date string
        // and a cumulative sum value
        func: (list, data) => {
            list.Add(new DepartmentOverviewDetailsViewModel.GraphJSONViewModel { XData = data.XData, YData = data.YData + list[list.Count - 1].YData });
            return list;
        }
    )
    .Skip(1) // skip the first dummy value we seeded the list with
    .ToArray();

另一种选择是编写一个通用的累积和函数,然后使用它:

public static class MyEnumerableExtensions {

    public static IEnumerable<double> CumulativeSum(this IEnumerable<double> @this) {
        var sum = 0;
        foreach (var value in @this) { sum += value; yield return sum; }
    }

}

// then to compute the sum you want
var rollingSum = ViewData.Select(m => m.YData).CumulativeSum();
var rollingSumWithDates = ViewData.Zip(rollingSum, (m, sum) => new DepartmentOverviewDetailsViewModel.GraphJSONViewModel { XData = m.XData, YData = sum })
    .ToArray();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    相关资源
    最近更新 更多