Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# singly linked list sum method

I want to find the sum of a simple list. But I can’t create a method Sum() without arguments. Please suggest possible solutions.

void Main()
{
    var chain1 = new Add(5)).Append(new Add(10)).Append(new add(15));
    var sum = chain.Sum();
}

public abstract class Strategy
{
    private Strategy _next;
    public Strategy Append(Strategy next)
    {
        if(_next == null){
            _next = next;
        } else {
            _next.Append(next);
        }
        
        return this;
    }
}

public class Add : Strategy
{
    int _num;
    public Add(int num) => _num = num;
    
    public int Sum()
    {
      ....
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@marsze is correct, there are much better ways of doing this… but I was able to modify it a bit and ended up with this non battle hardened code:

public abstract class Strategy
{
    protected Strategy _next;

    public Strategy Append(Strategy next)
    {
        if (_next == null)
        {
            _next = next;
        }
        else
        {
            _next.Append(next);
        }

        return this;
    }

    public abstract int Sum();
}

public class Add : Strategy
{
    int _num;
    public Add(int num) => _num = num;

    public override int Sum()
    {
        if (_next == null)
        {
            return _num;
        }

        return _num + _next.Sum();
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading