This question has come up while writing a simple text adventure game where your character has an inventory, which can include containers that also have things in them. I want a clean way to style the inventory output, like so:

You are carrying:
    a bag containing:
        a ring
    a backpack containing:
        a loaf of bread

Currently I just include the formatting in the result returned by the query, all in one shot. For example,

    result = QueryInventory(...recursively checks inventory adding multiples of tabs depending on nesting level...)

What I would like is a cleaner separation between content and presentation so that the query would just return a data structure that a separate pass could style.

But how should the styling pass handle the n-levels deep data structure? Just for example, how would a styling tool like CSS handle it? Do you need to procedurally generate the CSS once you have the data structure?


Your data structure should be recursive, like this:

public class Node
    public string Value { get; set; }
    public List<Node> Children { get; set; }

    public override string GetString()
        return this.Value;

Add four spaces to the beginning of the display line for each new recursion level. You can maintain a "level" variable that you pass along during the recursion (or make it static), increment it during each recursive call, and decrement it during each recursive return.

int indent = 0;
public string GetDisplayString()
    var s = new StringBuilder(new string(' ', indent) + node.ToString());
    if (node.Children != null)
        foreach (var child in node.Children)
            indent += 4;
            indent -= 4;
    return s.ToString();
  • thanks Robert, however this is basically what I have now (the indent is managed as you build the query response). Is there a case for returning just the data structure and then styling it as a separate procedure? – georgek Nov 28 '13 at 2:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.