简体   繁体   English

C#词典找不到字符串键

[英]C# Dictionary can't find string key

Am I going mad? 我会生气吗 Why does this return an exception!? 为什么这会返回异常!? Why can't it find the key? 为什么找不到钥匙? It's obviously there! 显然在那里!

public class Spanning {
    Dictionary<string, City> graph = new Dictionary<string, City>();

    public static void Main(string[] args) {
        new Spanning().Parse("file.in");
    }

    public void Parse(string f) {
        string[] citySeparator = new string[] {"--"};
        using (StreamReader reader = new StreamReader(f)) {
            string line;
            while((line = reader.ReadLine()) != null) {
                if (!line.Contains("--")) {
                    graph[line] = new City {name = line.Substring(0, line.Length - 1)};
                } else {
                    string[] split = line.Split(citySeparator, StringSplitOptions.None);
                    City city1 = graph[split[0]];
                }
            }
        }
    }

    class City {
        Dictionary<City, int> links = new Dictionary<City, int>();
        public string name;

        public override string ToString() {
            return name;
        }
    }
}

Input file contains just two rows: 输入文件仅包含两行:

"San Diego" 
"San Diego"--"San Antonio" [1319]

The first line of your file 文件的第一行

"San Diego" 

has a space character between the last " and the newline. 在最后一个"和换行符之间有一个空格字符。

Either fix you input file, or use Trim() to get rid of it: 修复您输入的文件,或使用Trim()摆脱它:

...
if (!line.Contains("--")) {
    graph[line.Trim()] = new City {name = line.Substring(0, line.Length - 1)};
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM