1

I've got a method that calls itself (recursion). It collects some data which I need to analyse. It collects the data in a DTO. DTO setup:

    public class SequenceDTO
    {
        public string sequence { get; set; }
        public List<Element> stateList { get; set; }

        public SequenceDTO()
        { }

        public SequenceDTO(string sequence, List<Element> stateList)
        {
            this.sequence = sequence;
            this.stateList = stateList;
        }
    }

This is how I initialize the recursion method:

string seq = "";
List<Element> elmList = new List<Element>();
initialSeqDTO.sequence = seq;
initialSeqDTO.stateList = elmList;
analyze(element, initialSeqDTO); //The recursion method

The recursion method:

public void handleEventAnalysis3(Element elm, SequenceDTO dto)
{
    SequenceDTO newSeqDTO = new SequenceDTO();
    List<Element> elmList = new List<Element>();
    elmList = dto.stateList;
    newSeqDTO.sequence = dto.sequence;
    newSeqDTO.stateList = elmList;

    newSeqDTO.stateList.Add(clientElement);

    if (!clientElement.Name.Equals("Initial"))
         handleEventAnalysis3(clientElement, newSeqDTO);

    if (clientElement.Name.Equals("Initial"))
    {
        sequenceList.Add(newSeqDTO);
    }
}

This is adding SequenceDTO's to the sequenceList. But the dto.stateList is the same for every SequenceDTO. How can this be?

2 Answers 2

2

You create a new List<Element>:

List<Element> elmList = new List<Element>();

But then you override it with the reference to your old list:

elmList = dto.stateList;

Instead, you can simply call ToList() to generate a new list:

newSeqDTO.stateList = dto.stateList.ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

Thought I had that covered with the new List<Element>() since it works with the sequence string. I will test it as the first thing in the morning (don't have the code near me) and then return with an accepted answer if it solved my problem.
0

because you assign the same list to each DTO:

 elmList = dto.stateList; // this reassigns the variable which makes you lose the newly created list
 newSeqDTO.sequence = dto.sequence;
 newSeqDTO.stateList = elmList

It works if you just remove this line:

elmList = dto.stateList;

1 Comment

This will work for sure. But it doesn't cover my requirement which I might not have specified enough in the question. The list in the old DTO could contain something that I still want in the new and this is lost in your answer. Your answer just make a new list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.