Sure this can be done by (ab?)using the LINQ Aggregate
method:
var differences = items.Aggregate(new { Previous = 0, List = new List<int>()}, (aggregate, current) =>
{
aggregate.List.Add(current - aggregate.Previous);
return new { Previous = current, aggregate.List};
}).List;
This creates a list of the differences you want. If you just want the Console.WriteLine
you can just aggregate with an int value and output the differences directly.
But I hope this is just for knowledge, in practice imo in this case just stick to the for loop, much cleaner.
Another option if you want to use the LINQ ForEach
and do your Console.WriteLine
you could do something like this:
var previous = 0;
items.ForEach(item =>
{
if (previous.HasValue)
Console.WriteLine($"{item} - {previous} = {item - previous}");
previous = item;
});
But once again nothing wrong with using the for
loop. I really feel people go blind in their desire to use LINQ for everything.
EDIT: I see you asked to ignore the first "weird" output, basically skipping the first value, this is how that would look for both cases:
var differences = items.Aggregate(new { Previous = (int?)null, List = new List<int>()}, (aggregate, current) =>
{
if (aggregate.Previous.HasValue)
aggregate.List.Add(current - aggregate.Previous.Value);
return new { Previous = (int?)current, aggregate.List};
}).List;
int? previous = null;
items.ForEach(item =>
{
if (previous.HasValue)
Console.WriteLine($"{item} - {previous} = {item - previous}");
previous = item;
});