Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to append an array value inside a Dictionary<string,string[]>

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading