Search code examples
c#linqlinq-to-sqlsumsubtraction

Repeated subtraction of rows from a column using LINQ and C#


I would like to repeatedly subtract rows from a column in a table in my database using LINQ. My table is as shown

ID       Numbers

1         488  
2         612 
3         803 
4        1082 
5        1310 
6        1586 
7        1899 

I'd like to take 612 and subtract it with 488 and store the value.

Afterwards take 803 and subtract it with 612 and store the value.

Do that for every number

1082 - 803

1310 - 1082

1586 - 1310

1899 - 1586 

At the end i'd like to sum the obtained values.

Is there a specific function i could use? I've tried using for loop but i just can't seem to manage to put the pieces together for it to work. Can someone help?


Solution

  • This is very simple. Just get total sum of item - previous item

    private int GetSumOfSubtractions(int[] numbers)
    {
        if (numbers.Length == 0) return 0;
        if (numbers.Length == 1) return numbers[0];
        int sum = 0;
        for (int i = 1; i < numbers.Length; i++)
        {
            sum += numbers[i] - numbers[i - 1];
        }
        return sum;
    }
    

    A little math behind this.

    612 - 488 + 803 - 612 + 1082 - 803 + 1310 - 1082 + 1586 - 1310 + 1899 - 1586
    ^           ^^    ^            ^^
    

    As you can see middle numbers cancel each other and become 0 and only first item and last item remains.

    So 1899-488 is the answer.