Skip to content

Instantly share code, notes, and snippets.

@ulve
Last active February 28, 2018 11:34
Show Gist options
  • Save ulve/7a82421d7698ce1187c429d84aa1564e to your computer and use it in GitHub Desktop.
Save ulve/7a82421d7698ce1187c429d84aa1564e to your computer and use it in GitHub Desktop.
Sum list
public void Calc()
{
var lists = new List<List<int>>
{
new List<int> { 1, 1, 2, 2 },
new List<int> { 1, 1, 1, 1 },
new List<int> { 1, 2, 3, 4 },
new List<int> { 9, 1, 2, 1, 2, 9 }
};
foreach (var list in lists)
{
var sum = list.Aggregate(new { Sum = 0, LastAdded = list.Last() }, (acc, val) => new {
Sum = acc.Sum + val - (acc.LastAdded != val ? acc.LastAdded : 0),
LastAdded = val
}).Sum;
// Alternativ
list.Add(list.First());
var sum2 = list.Zip(list.Skip(1), (a, b) => new { a, b }).Where(a => a.a == a.b).Sum(a => a.a);
Console.WriteLine($"{sum} == {sum2}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment