我需要构建一个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)
.........
有关如何构建此查询的任何帮助吗?
非常感谢!
答案 0 :(得分: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查询将要生成的代码那样清晰。这也不规模。例如,如果它只是用“老式的方式”写出来的话,包括多年的数据会变得更加毛茸茸。
答案 1 :(得分: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});