Applying a method to members of a class
<p>Say I have a C# class:</p>

<pre><code>public class Node
{
    public double A { get; set; }
    public double B { get; set; }
}
</code></pre>

<p>...and another class that includes a list of objects of that type:</p>

<pre><code>public Buffer
{
    private List&lt;Node&gt; _nodes;
    ...
}
</code></pre>

<p>Now, say I need to calculate the sum of the values of A for the Node objects in the _nodes list. Then (separately) calculate the sum of B. Is there a way to do this using a 'generic' Sum() method, without having to duplicate code?</p>

<p>For example, one approach could be:</p>

<pre><code>public class Buffer
{
    ...

    private double SumA()
    {
        double sum;

        foreach (Node node in _nodes)
        {
            sum += node.A;
        }

        return sum;
    }

    private double SumB()
    {
        double sum;

        foreach (Node node in _nodes)
        {
            sum += node.B;
        }

        return sum;
    }
}
</code></pre>

<p>The problem here is that the basic algorithm implemented by SumA() and SumB() is the same but in the case above is duplicated. This is compounded if Node has more properties, which needs summing, or if Sum() is a much more complicated process (both of which are true in the case I'm currently refactoring).</p>

<p>So to put the question another way, is there a way I can have a single Sum() method but have it operate on whichever member(s) of class Node within the list that I need to sum?</p>
