0

我需要构建一个 Linq 查询,它将显示如下结果:

Data:

Sales   Month
----------------------
10      January
20      February
30      March
40      April
50      May
60      June
70      July
80      August
90      September
100     October
110     November
120     December

我需要根据这种情况获得结果: 月 x = 月 x + 上个月 ,这将导致:

Sales   Month
--------------------
10      January
30      February (30 = February 20 + January 10)
60      March    (60 = March 30 + February 30)
100     April    (100 = April 40 + March 60)
.........

对如何构建此查询有任何帮助吗?

非常感谢!

4

2 回答 2

0

既然你想在 LINQ 中使用它...

void Main()
{
    List<SaleCount> sales = new List<SaleCount>() {
        new SaleCount() { Sales = 10, Month = 1 },
        new SaleCount() { Sales = 20, Month = 2 },
        new SaleCount() { Sales = 30, Month = 3 },
        new SaleCount() { Sales = 40, Month = 4 },
        ...
    };

    var query = sales.Select ((s, i) => new
    {
        CurrentMonth = s.Month,
        CurrentAndPreviousSales = s.Sales + sales.Take(i).Sum(sa => sa.Sales)
    });
}

public class SaleCount
{
    public int Sales { get; set; }
    public int Month { get; set; }
}

...但在我看来,在这种情况下,提出一些花哨的 LINQ 并不像写出 LINQ 查询将生成的代码那样清晰。这也无法扩展。例如,如果只是以“老式方式”写出,则包含多年价值的数据会变得更加棘手。

于 2012-06-27T02:30:35.603 回答
0

如果您不想将每个月以前的所有销售额相加,则必须以某种方式跟踪总销售额。Aggregate 函数可以正常工作,因为我们可以构建一个列表并使用它的最后一个元素作为当前总数来计算下一个元素。

var sales = Enumerable.Range(1,12).Select(x => x * 10).ToList();
var sums = sales.Aggregate(new List<int>(), (list, sale) => list.Concat(new List<int>{list.LastOrDefault() + sale});
于 2012-06-27T04:35:23.127 回答