简体   繁体   English

C#:将项目添加到列表时,以前的列表项目也会被该项目覆盖。 为什么?

[英]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#. 我已经在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. 该方法返回List<List<string>> ,该List<List<string>>记录List经历的所有步骤和更改,所选的变量等。

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. 其他答案提到在for循环中实例化,但是我认为这不适用于此处。

What may be the problem? 可能是什么问题?

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). 因此,一旦修改set步骤中的每个元素都会显示更新后的值(它们指向同一对象)。

Try change steps.Add(set); 尝试更改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. steps.Add(set.ToList())steps.Add(new List<int>(set)) ,它们应该创建新列表,而不是引用旧列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM