LINQ to SQL和有序结果的运行总数

我想在DataGridView显示一个客户的会计logging,我想要一个列显示其余额的运行总额。 我这样做的旧方法是获取数据,循环遍历数据,并逐行添加到DataGridView ,并计算当时的总运行总数。 瘸。 我宁愿使用LINQ to SQL,或LINQ(如果LINQ to SQL不可能的话)来计算运行总数,所以我可以将DataGridView.DataSource设置为我的数据。

这是我拍摄的一个超简单的例子。 说我有以下class级。

 class Item { public DateTime Date { get; set; } public decimal Amount { get; set; } public decimal RunningTotal { get; set; } } 

我想要一个可以生成如下结果的L2S或LINQ语句:

  Date Amount RunningTotal 12-01-2009 5 5 12-02-2009 -5 0 12-02-2009 10 10 12-03-2009 5 15 12-04-2009 -15 0 

请注意,同一date可能有多个项目(12-02-2009)。 计算运行总数之前应按date对结果进行sorting。 我猜这意味着我需要两条语句,一条是获取数据并对其进行sorting,另一条是执行运行总计算。

我希望Aggregate能够做到这一点,但是它并不像我希望的那样工作。 或者,我可能无法弄清楚。

这个问题似乎是在我想要的同样的东西后,但我不明白如何接受/唯一的答案解决我的问题。

任何想法如何把这个closures?

编辑从亚历克斯和DOK的答案,这是我结束了:

 decimal runningTotal = 0; var results = FetchDataFromDatabase() .OrderBy(item => item.Date) .Select(item => new Item { Amount = item.Amount, Date = item.Date, RunningTotal = runningTotal += item.Amount }); 

使用闭包和匿名方法:

 List<Item> myList = FetchDataFromDatabase(); decimal currentTotal = 0; var query = myList .OrderBy(i => i.Date) .Select(i => { currentTotal += i.Amount; return new { Date = i.Date, Amount = i.Amount, RunningTotal = currentTotal }; } ); foreach (var item in query) { //do with item } 

这个怎么样:(信贷来源 )

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { delegate string CreateGroupingDelegate(int i); static void Main(string[] args) { List<int> list = new List<int>() { 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 69, 2007}; int running_total = 0; var result_set = from x in list select new { num = x, running_total = (running_total = running_total + x) }; foreach (var v in result_set) { Console.WriteLine( "list element: {0}, total so far: {1}", v.num, v.running_total); } Console.ReadLine(); } } } 

如果这还没有得到答复,我有一个解决scheme,我一直在使用我的项目。 这与Oracle分区组非常相似。 关键是让运行总计中的where子句与原始列表匹配,然后按date进行分组。

 var itemList = GetItemsFromDBYadaYadaYada(); var withRuningTotals = from i in itemList select i.Date, i.Amount, Runningtotal = itemList.Where( x=> x.Date == i.Date). GroupBy(x=> x.Date). Select(DateGroup=> DateGroup.Sum(x=> x.Amount)).Single(); 

总计也可以用来获得运行总额:

 var src = new [] { 1, 4, 3, 2 }; var running = src.Aggregate(new List<int>(), (a, i) => { a.Add(a.Count == 0 ? i : a.Last() + i); return a; }); 
 using System; using System.Linq; using System.Collections.Generic; public class Program { public static void Main() { var list = new List<int>{1, 5, 4, 6, 8, 11, 3, 12}; int running_total = 0; list.ForEach(x=> Console.WriteLine(running_total = x+running_total)); } }