0

I'm new to C# and looking for a smart way to reduce redundancy in my code.

 public double sumx()
    {
        double temp = 0;
        foreach (var item in col)
        {
            temp= temp + item.x;
        }
        return temp;
    }
    public double sumy()
    {
        double temp = 0;
        foreach (var item in col)
        {
            temp = temp + item.y;
        }
        return temp;
    }

col is of type List< Point > and Point is a class by my own, which provides two properties (x and y) and an constructor Point(x,y).

I want now the sum of all x, respectively sum of all y.

I'm looking for a more generalized sum function, which maybe uses delegates or Lambda expressions. I have no Idea how to do this in a smart c# way.

Thanks in advance

  • 2
    Check out [`Enumerable.Sum`](https://msdn.microsoft.com/en-us/library/system.linq.enumerable.sum(v=vs.110).aspx) – juharr Oct 06 '15 at 19:24

1 Answers1

5

Sure, use the Sum extension method from Linq:

public double sumx()
{
    return col.Sum(item => item.x);
}
public double sumy()
{
    return col.Sum(item => item.y);
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • 2
    Well, at this point making a function for this has no great value. – Steve Oct 06 '15 at 19:26
  • 2
    @Steve other than shortening the call and saving the caller from writing a lambda, but yes, it's not a huge gain. Also would be required if `x` or `y` were private. – D Stanley Oct 06 '15 at 19:29
  • I am just suggesting that this could remove at all the need of a specific method and probably gives a better clue to what's happening. But I am digressing. Your answer is absolutely correct. – Steve Oct 06 '15 at 19:34
  • Thanks D Stanley and Steve, that's the c# way I was looking for. I just need the results of the two functions for another function which calculcates regression coefficients. But the Linq way is so short (as mentioned by Steve), that I will use it directly in the function which calculates the regression coefficients. So I can remove sum x/y. – user1315449 Oct 06 '15 at 19:51