我無法將元素正確添加到Dictionary<string, List<string>>具有List<string>相似值的 a 中。每次我輸入一個以 List 作為值的新鍵時,之前輸入的鍵的值都會被最后輸入的 List 覆寫。
Dictionary<string, List<string>> videosBloqueDict = new Dictionary<string, List<string>>();
List<string> videosResult = new List<string>();
string[] bloques = Directory.GetDirectories(path).Select(Path.GetFileName).ToArray();
foreach(var bloque in bloques)
{
string[] videos = Directory.GetFiles(path "\\" bloque).Select(Path.GetFileName).ToArray();
videosResult.Clear();
foreach (var video in videos)
{
string[] val = video.Split(' ').Skip(1).ToArray();
string result = string.Join(" ", val);
videosResult.Add(result); **//list with the new values ??to enter the dictionary**
}
videosBloqueDict.Add(bloque, videosResult);
}
例如:
string[] bloques = {01:00, 02:00, 03:00}(我要添加的鍵)
實際字典:
- 鍵 = 01:00,值 = {yx, yy, xxx}
- 鍵 = 02:00,值 = {yx, yy, xxx}
- 鍵 = 03:00,值 = {yx, yy, xxx}
預期字典:
- 鍵 = 01:00,值 = {xxx,yxy}
- 鍵 = 02:00,值 = {xyy,yyx,yyy,yyx,yy}
- 鍵 = 03:00,值 = {yx, yy, xxx}
uj5u.com熱心網友回復:
串列是參考型別,videosResult對單個串列的參考也是如此。回圈的每一輪,您都會清除同一個串列,然后將對該同一個串列的另一個參考添加到字典中。這就是為什么您最終會為字典中的每個條目得到相同的結果:它是重復多次的同一個串列。
您需要在每個回圈上創建一個新串列,當您使用它時,由于您實際上不需要回圈之外的串列本身,您應該直接在其中宣告它:
// don't declare videosResult here
foreach(var bloque in bloques)
{
string[] videos = ...;
var videosResult = new List<string>(); // create a new list instead of clearing the original one
// rest of the method
}
順便說一句,你不需要這么多的呼叫ToArray():如果你要立即開始列舉這些值,只需將它們保留為IEnumerable<T>并且,好吧,列舉它們。ToArray在這里創建不必要的副本,因為它只應在您真正需要陣列時使用。
uj5u.com熱心網友回復:
Dictionary<string, List<string>> videosBloqueDict = new Dictionary<string, List<string>>();
string[] bloques = Directory.GetDirectories(path).Select(Path.GetFileName).ToArray();
foreach(var bloque in bloques)
{
List<string> videosResult = new List<string>();
string[] videos = Directory.GetFiles(path "\\" bloque).Select(Path.GetFileName).ToArray();
foreach (var video in videos)
{
string[] val = video.Split(' ').Skip(1).ToArray();
string result = string.Join(" ", val);
videosResult.Add(result); **//list with the new values ??to enter the dictionary**
}
videosBloqueDict.Add(bloque, videosResult);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430284.html
