user7716925
user7716925

Reputation:

C#: When adding an Item to a List, the previous List Items get overwritten with the Item as well. Why?

I have implemented the insertion sort algorithm in C#. The method returns a List<List<string>> which records all of the steps and changes that the List experienced, variables that were selected etc.

Here is the method:

public List<List<int>> SortStepByStep(List<int> set)
{
    List<List<int>> steps = new List<List<int>>();
    steps.Add(set); 

    for (int c1 = 1; c1 < set.Count; c1++)
    {
        Console.WriteLine(steps[0][0].ToString());

        int item = set[c1];

        set.Add(item);
        steps.Add(set);
        set.RemoveAt(set.Count - 1);
        // ^^^^ This is just to visually display what number is being selected.

        set.RemoveAt(c1);

        steps.Add(set); 

        bool inserted = false;
        for (int c2 = 0; c2 < c1; c2++)
        {
            if ((set[c2] > item || c2 == c1 - 1) && !inserted)
            {
                set.Insert((set[c2] <= item && (c2 == c1 - 1) ? c2 + 1 : c2), item);
                steps.Add(set); 
                inserted = true; 
                break;
                // Added the break in anyway because sometimes the inserted boolean failed to work.
            }
        }
    }
    return steps;
}

What the method actually returns is just the final sorted list at every index of 'steps'. I've followed it through with writing the 'steps' to the console and can see it gradually changing, but do not understand why.

Other answers mention instantiating within the for loop, but I don't think that's applicable here.

What may be the problem?

Upvotes: 0

Views: 722

Answers (1)

artgdev
artgdev

Reputation: 184

Your steps list holding references to the same collection. Because of that, once you modify set, each element of the steps will show you updated value (they are pointing to the same object).

Try change steps.Add(set); to steps.Add(set.ToList()) or steps.Add(new List<int>(set)), that should create new list instead of referencing old one.

Upvotes: 1

Related Questions