-1

I have a list of integers:

List<Int32?> numbers = new List<Int32?> { 2, 1, 3, null, 6, 7 }

I need to get a List with the difference between two consecutive values, so the result would be:

{ null, -1, 2, null, null, 1 }

null
-1 = 1-2
2 = 3-1
null = null-3
null = 6-null
1 = 7-6

Can this be done using LINQ?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

2 Answers2

1

Don't think you can do it with link but you can do it like that:

List<int?> Method(List<int?> list)
    {
        int? priv = null;
        List<int?> ret = new List<int?>();
        foreach (var cornt in list)
        {
            if (cornt == null || priv == null) ret.Add(null);
            else ret.Add(cornt - priv);
            priv = cornt;          
        }

        return ret;
    }
Ethan.S
  • 385
  • 3
  • 13
1

Can you do it with LINQ? Yes:

var diffs = numbers.Select((_, i) => i == 0 ? null : numbers[i] - numbers[i - 1]);

Should you do it with LINQ? Probably not.

aquinas
  • 23,318
  • 5
  • 58
  • 81