I'm trying to create a Graph data structure and sort it using Topological Sorting. My code is as below:
public class Node<T>
{
// Private member-variables
private T data;
private NodeList<T> neighbors = null;
public Node() { }
public Node(T data) : this(data, null) { }
public Node(T data, NodeList<T> neighbors)
{
this.data = data;
this.neighbors = neighbors;
}
public T Value
{
get
{
return data;
}
set
{
data = value;
}
}
protected NodeList<T> Neighbors
{
get
{
return neighbors;
}
set
{
neighbors = value;
}
}
}
public class NodeList<T> : List<Node<T>>
{
public NodeList() : base() { }
public Node<T> FindByValue(T value)
{
// search the list for the value
foreach (Node<T> node in this)
if (node.Value.Equals(value))
return node;
// if we reached here, we didn't find a matching node
return null;
}
}
public class GraphNode<T> : Node<T>
{
private List<int> costs = null;
public GraphNode() : base()
{
}
public GraphNode(T value) : base(value)
{
}
public GraphNode(T value, NodeList<T> neighbors) : base(value, neighbors)
{
}
new public NodeList<T> Neighbors
{
get
{
if (base.Neighbors == null)
base.Neighbors = new NodeList<T>();
return base.Neighbors;
}
}
public List<int> Costs
{
get
{
if (costs == null)
costs = new List<int>();
return costs;
}
}
}
public class Graph<T>
{
private NodeList<T> nodeSet;
public List<GraphNode<T>> Sort(Graph<T> graph, Func<GraphNode<T>, IEnumerable<GraphNode<T>>> neighBours)
{
var sorted = new List<GraphNode<T>>();
var visited = new Dictionary<GraphNode<T>, bool>();
foreach (var item in graph.Nodes)
{
var _tempItem = item as GraphNode<T>;
Visit(_tempItem, neighBours, sorted, visited);
}
return sorted;
}
public void Visit(GraphNode<T> item, Func<GraphNode<T>, IEnumerable<GraphNode<T>>> neighBours, List<GraphNode<T>> sorted, Dictionary<GraphNode<T>, bool> visited)
{
bool inProcess = false;
var alreadyVisited = visited.TryGetValue(item, out inProcess);
if (alreadyVisited)
{
if (inProcess)
{
throw new Exception("Cyclic dependency found.");
}
}
else
{
visited[item] = true;
var dependencies = neighBours(item);
if (dependencies != null)
{
foreach (var dependency in dependencies)
{
Visit(dependency, neighBours, sorted, visited);
}
}
visited[item] = false;
sorted.Add(item);
}
}
}
The call to Sort method is made as below:
List<GraphNode<string>> lstSorted = _graph.Sort(_graph, x => x.Neighbors);
But I'm getting below error in the call for x.Neighbors
:
Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
Can someone please tell me how to fix this?