[英]Problem adding an item into a 2 dimension List in C# (unexpected behavior)
你能告訴我為什么我從這段代碼中得到以下結果
public static void CountSort(List<List<string>> arr)
{
for (int i = 0; i < arr.Count / 2; i++)
arr[i][1] = "-";
List<List<string>> result = Enumerable.Repeat(new List<string>(), arr.Count).ToList();
for (int i = 0; i < arr.Count; i++)
{
string tempValue = arr[i][1];
int index = int.Parse(arr[i][0]);
result[index].Add(tempValue);
}
}
結果是多維字符串列表。 每當循環通過時,它都會將該臨時值添加到所有子 arrays 中,而不是將其添加到我要根據索引添加的那個中。
我現在正在努力弄清楚為什么會這樣。
Output 看起來像這樣:
List<List<string>("1"), List<string>("1"),List<string>("1")>
Output 我期待的是:
List<List<string>(), List<string>("1"), List<string>()>
看看這一行:
result = Enumerable.Repeat(new List<string>(), arr.Count).ToList();
這將創建一個List<string>
實例並在生成的可枚舉/列表中重復此實例。 同樣,這里只創建了一個List<string>
實例。 無論您在result上使用哪個索引來獲取子列表,它始終是相同的List<string>實例。
因此,您的代碼將臨時值添加到所有子列表,因為所有子列表實際上只是同一個List<string>實例。
解決方案:不要使用Enumerable.Repeat
(它只是重復給定的List<string>實例而不是創建新的List<string>實例),只需以老式方式執行並自己創建所有必需的List<string>實例:
List<List<string>> result = new();
for (int i = 0; i < arr.Count; ++i)
result.Add(new List<string>());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.