【发布时间】:2015-11-24 10:29:19
【问题描述】:
尝试读取 csv 文件,并获取流中的第一个单词,将其放入字典中,同时将以下单词添加到该字典中的列表中。
但是,我发现(在调试过程中)当我决定在循环中清除列表时,它之前添加到字典中的所有值也会被清除。我想我错误地假设它复制了列表,它实际上只是引用了同一个列表?我应该在每次迭代时创建一个新列表吗?代码如下:
public class TestScript : MonoBehaviour {
// Use this for initialization
void Start() {
Dictionary<string, List<string>> theDatabase = new Dictionary<string, List<string>>();
string word;
string delimStr = ",.:";
char[] delimiter = delimStr.ToCharArray();
List<string> theList = new List<string>();
using (StreamReader reader = new StreamReader("testComma.csv")) {
while (true) {
//Begin reading lines
string line = reader.ReadLine();
if (line == null) {
break;
}
//Begin splitting lines, adding to array.
string[] split2 = line.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
//Loop to hold the first word in the stream
for(int i = 0; i <= 0; i++) {
word = split2[i];
//loop to hold the following words in to list.
for (int y = 1; y < split2.Length; y++) {
theList.Add(split2[y]);
}
//Add word/list combo in to the database
theDatabase.Add(word, theList);
//clear the list.
theList.Clear();
}
}
}
foreach (KeyValuePair<string, List<string>> pair in theDatabase) {
string keys;
List<string> values;
keys = pair.Key;
values = pair.Value;
print(keys + " = " + values);
}
}
}
底部的 foreach 循环只是为了让我可以看到结果。此外,由于我是初学者,因此欢迎对本文的编写方式提出任何批评。
【问题讨论】:
-
是的,您需要复制列表并将其添加到字典中,或者在外部循环的每次迭代中创建一个新列表
标签: c# string list dictionary streamreader