Advertisements
For some reason I cannot append a string variable to string[] value in Dictionary<string;string[]>
I am trying to make a Graph C# class for practice and i ran into a problem: I use Dictionary<string, string[]> graph
to make a structure like this:
"Node1":[connection1,connection2,connection3]
"Node2":[connection1,connection2,connection3]
"Node3":[connection1,connection2,connection3]
...
I have a method to append a connections array value:
// from Graph class
private Dictionary<string, string[]> graph;
public void AddEdge(string NodeName, string EdgeName)
{
graph[NodeName].Append(EdgeName);
}
And use it like this:
//from Main
Graph g = new Graph();
string[] Nodes = { "node1", "node2", "node3" };
string[][] Edges = { new[] { "node1", "nodeToEdgeTo" }, new[] { "node2", "nodeToEdgeTo" } };
//nodeToEdgeTo are nodes like "node2" or "node3"
foreach (var i in Edges)
{
g.AddEdge(i[0], i[1]);
}
But as a result i get empty values for some reason:
"Node1":[]
"Node2":[]
"Node3":[]
I have no idea why
>Solution :
Instead of an array, you might want a List isntead: Dictionary<string, List<string>>
.
Then you could do this:
public void AddEdge(string NodeName, string EdgeName)
{
graph[NodeName].Add(EdgeName);
}