Search code examples
c#.netvisual-studiolinqpad

Visualize data structures such as trees and graphs in C#


I am using C# with LINQPad. How can I visualize graphs and trees?

For example, if I create a Tree data structure like this:

public class BinaryTree<T>()
{
    public T Value { get; set; }
    public BinaryTree<T> LeftChild { get; set; }
    public BinaryTree<T> RightChild { get; set; }
    
    //Other methods:
}

I would like a simple way to display it when I execute the program, e.g., like this:

Binary tree graph with 7 nodes


Solution

  • Your best bet might be to use Microsoft Automatic Graph Layout. This is what LINQPad uses for the syntax tree visualizer.

    In LINQPad 5 you can use this library just by adding a reference to the Microsoft.MSAGL.GraphViewerGDIGraph NuGet package. You can then do this:

    var graph = new Graph ("graph");
    
    graph.AddEdge ("A", "B");
    graph.AddEdge ("B", "C");
    graph.AddEdge ("A", "C").Attr.Color = Microsoft.Msagl.Drawing.Color.Green;
    
    new GViewer() { Graph = graph, ToolBarIsVisible = false }.Dump();
    

    Unfortunately, this won't work in LINQPad 6 (from .NET Core 3.1) because Microsoft.MSAGL.GraphViewerGDIGraph is a .NET Framework package with a dependency on the WinForms toolbar control which was removed in .NET Core 3.1. However, MSAGL is open source and it's fairly easy to remove the dependency, as I've done here:

    https://github.com/albahari/automatic-graph-layout