【问题标题】:C#: When adding an Item to a List, the previous List Items get overwritten with the Item as well. Why?C#:将项目添加到列表时,之前的列表项目也会被该项目覆盖。为什么?
【发布时间】:2017-03-15 18:37:44
【问题描述】:

我已经在 C# 中实现了插入排序算法。该方法返回一个List<List<string>>,它记录了List经历的所有步骤和更改、选择的变量等。

方法如下:

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;
}

该方法实际返回的只是“步骤”每个索引处的最终排序列表。我已经完成了将“步骤”写入控制台并且可以看到它逐渐变化,但不明白为什么。

其他答案提到在 for 循环中实例化,但我认为这不适用于此处。

可能是什么问题?

【问题讨论】:

  • 问题是您正在向您的steps 添加一个相同的列表对象reference(它不会为您制作副本)。将 全部 steps.Add(set); 替换为 steps.Add(set.ToList());
  • 非常感谢,我不明白它是如何工作的。感谢您为我节省了很多时间!

标签: c# list for-loop instantiation insertion-sort


【解决方案1】:

您的步骤列表包含对同一集合的引用。因此,一旦您修改 setsteps 的每个元素都会显示更新后的值(它们指向同一个对象)。

尝试将steps.Add(set); 更改为steps.Add(set.ToList())steps.Add(new List&lt;int&gt;(set)),这应该会创建新列表而不是引用旧列表。

【讨论】:

  • 非常感谢您的回答,我需要更仔细地阅读理论/msdn 页面!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 1970-01-01
  • 1970-01-01
  • 2020-06-23
  • 2015-10-06
  • 1970-01-01
相关资源
最近更新 更多