Andreas
Andreas

Reputation: 692

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]

Upvotes: 1

Views: 2461

Answers (1)

sloth
sloth

Reputation: 101142

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:

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

Upvotes: 7

Related Questions