![](/img/trans.png)
[英]How to add a Dictionary<string,List<string>> to a DataTable in C#?
[英]How to add a string list to a Dictionary correctly
我無法將元素正確添加到具有List<string>
之類值的Dictionary<string, List<string>>
中。 每次我輸入一個帶有列表作為值的新鍵時,先前鍵的值都會被最后輸入的列表覆蓋。
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}
列表是引用類型,因此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
在這里創建了不必要的副本,因為它只應在您確實需要數組時使用。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.