So I have an object(lets call it the Head) which has a list of objects C(C1,C2,C3,...) , T(T1,T2,...) and M(M1,M2,...) and all of these are interrelated like for e.g.
Head -> C1,C2,C3 , T1 , T2 , M1 , M2
T1 -> C1,C2
T2 -> C2,C3
M1 -> C1, C2,C3
M2 -> C1, C2
where "->" implies "related to"
So Head has 7 successors and 0 predecessors
T1 has 1 predecessor(Head ) and 2 successors(C1,C2)
M1 has 1 predecessor(Head ) and 3 successors(C1,C2,C3)
and so on
I thought of creating a class with successors and predecessors as its properties but am not sure how to build this graph like structure from the Head object?
That really depends on what you need to do with the graph. The easiest storage would be a List<Node> where each Node object contains links to its predecessors and successors. (And some data of course)
You can do pretty much everything on this list, but an algorithm might have a certain data structure which makes it more efficient/faster. Convert to this as needed. For initialization for example:
class Example
{
public List<Node> InitGraph()
{
var nodes = new Dictionary<string, Node>();
nodes.Add("Head", new Node("Head"));
nodes.Add("T1", new Node("T1"));
nodes.Add("T2", new Node("T2"));
// While that works, a method is nicer:
nodes.Add("C1");
// These two lines should really be factored out to a single method call
nodes["Head"].Successors.Add(nodes["T1"]);
nodes["T1"].Predecessors.Add(nodes["Head"]);
nodes["Head"].Successors.Add(nodes["T2"]);
nodes["T2"].Predecessors.Add(nodes["Head"]);
// Yes. Much nicer
nodes.Connect("Head", "C1");
nodes.Connect("T1", "C1");
nodes.Connect("T2", "C1");
var nodelist = new List<Node>(nodes.Values);
return nodelist;
}
}
public static class NodeHelper
{
public static void Add(this Dictionary<string, Node> dict, string nodename)
{
dict.Add(nodename, new Node(nodename));
}
public static void Connect(this Dictionary<string, Node> dict, string from, string to)
{
dict[ from ].Successors.Add(dict[ to ]);
dict[ to ].Predecessors.Add(dict[ from ]);
}
}
public class Node
{
public string Name { get; set; }
public int Coolness { get; set; }
public List<Node> Predecessors { get; set; }
public List<Node> Successors { get; set; }
public Node()
{
Coolness = 1;
}
public Node(string name) : this()
{
this.Name = name;
}
}
For the actual initialization phase, I'd read it from a file. First all Nodes and then all Edges connecting them. Make some nice Load/Save Methods to make sure it's all consistent.
While I have expanded the example (and it compiles) I left testing to the reader. It should give you a good starting point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With