[英]C#: When adding an Item to a List, the previous List Items get overwritten with the Item as well. Why?
我已經在C#中實現了插入排序算法。 該方法返回List<List<string>>
,該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循環中實例化,但是我認為這不適用於此處。
可能是什么問題?
您的步驟將列出對同一集合的引用 。 因此,一旦修改set , 步驟中的每個元素都會顯示更新后的值(它們指向同一對象)。
嘗試更改steps.Add(set);
到steps.Add(set.ToList())
或steps.Add(new List<int>(set))
,它們應該創建新列表,而不是引用舊列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.