first_page the funky knowledge base
personal notes from way, _way_ back and maybe today

LINQ to Objects Code: A Running Total

class Item { public int Number { get; set; } public int Sum { get; set; } }

[TestMethod] public void TinyTest() { var set = new List<Item> { new Item{Number=1}, new Item{Number=2}, new Item{Number=3}, new Item{Number=4}, new Item{Number=5}, new Item{Number=6}, new Item{Number=7}, new Item{Number=8}, new Item{Number=9}, new Item{Number=10}, new Item{Number=11}, new Item{Number=12}, new Item{Number=13}, new Item{Number=14}, new Item{Number=15} };

set.ForEach(x =&gt; x.Sum = x.Number + (set.Where(x2 =&gt; x2.Number &lt; x.Number).Sum(x3 =&gt; x3.Number)));
var sortedSet = set.OrderByDescending(x=&gt;x.Number);

foreach(var item in sortedSet)
{
    TestContext.WriteLine(&quot;{0},{1}&quot;, item.Number, item.Sum);
}

}

/*

Test Results:

15,120 14,105 13,91 12,78 11,66 10,55 9,45 8,36 7,28 6,21 5,15 4,10 3,6 2,3 1,1

*/

[http://en.wikipedia.org/wiki/Running_total]

mod date: 2010-02-19T21:29:52.000Z