Search code examples
c#listdictionarydependency-graph

Dependency Graph using Dictionaries and Lists


I'm in the middle of working on a dependency graph, and I'm having trouble with properly adding my dependents and dependees.

I have it set up like:

private List<Tuple<string, string>> DG;
private Dictionary<string, List<string>> dependants;
private Dictionary<string, List<string>> dependees;

And I'm trying to add to my dictionaries like:

for (int i = 0; i < DG.Count; i++)
{
    dependants.Add(DG[i].Item1, new List<string>().Add(DG[i].Item2);
}

It gives me the error "Argument2: Cannot convert from void to System.Collections.Generic.List" where I try to add to a new list in the second parameter. I think I know why I'm getting errors, but I am having trouble thinking of an alternative way to correctly add into the dictionaries.

My goal is something like this:

//DG = {("a", "b"), ("a", "c"), ("b", "d"), ("d", "d")}
//     dependents("a") = {"b", "c"}
//     dependents("b") = {"d"}
//     dependents("c") = {}
//     dependents("d") = {"d"}
//     dependees("a") = {}
//     dependees("b") = {"a"}
//     dependees("c") = {"a"}
//     dependees("d") = {"b", "d"}

So ("a", "b") means that "b" is a dependent of "a" and "a" is a dependee of "b"


Solution

  • Its a little longer than your code, but this might be what you need:

    for (int i = 0; i < DG.Count; i++)
    {
        if (!dependants.ContainsKey(DG[i].Item1)) 
        {
            List<string> temp = new List<string>();
            temp.add(DG[i].Item2); 
            dependants.Add(DG[i].Item1, temp);
        }
        else
            dependants[DG[i].Item1].Add(DG[i].Item2);
    }
    

    Hopefully the longer code helps you understand the flow. This is only for making the dependants. Also, you were missing a bracket close in your original code:

    dependants.Add(DG[i].Item1, new List<string>().Add(DG[i].Item2);
    

    should be

    dependants.Add(DG[i].Item1, new List<string>().Add(DG[i].Item2));