title: C# parsing custom hierarchical expression - build tree
body: <p>I'm building custom resource provider driven by very custom language. In order to do that I have to create tree data structure from custom expression. Let me explain:</p>
  
  <pre><code>f1(f2,f3,f6(f4),f5)
  </code></pre>
  
  <p>Above, is example of my custom expression , from which I want to build tree. Root - <code>f1</code>, has children : <code>f2</code>, <code>f3</code>, <code>f4</code>, <code>f5</code>. But <code>f4</code> also has it's own children. </p>
  
  <p>I've written solution for this problem, but I want to find better way to achieve this goal.</p>
  
  <pre><code>class Node
  {
      public string val;
      public List&lt;Node&gt; child = new List&lt;Node&gt;();
  }
  
  private Node parseInput(string input, int index)
  {
      string nodeName = findToken(input,ref index);
      Node tmp = new Node() { val = nodeName };
      tmp.child = expandNodes(input, ref index);
      return tmp;
  }
  
  
  private List&lt;Node&gt; expandNodes(string input, ref int index)
  {
      List&lt;Node&gt; res = new List&lt;Node&gt;();
      while (!char.IsLetterOrDigit(input[index++]) &amp;&amp; index &lt; input.Length) ;
      index--;
  
      while (index &lt; input.Length)
      {
          if (checkNext(input, index, ')'))
          {
              while (!char.IsLetterOrDigit(input[index++]) &amp;&amp; index &lt; input.Length) ;
              index--;
              return res;
          }
          Node tmp = new Node() { val = findToken(input,ref index) };
          if (checkNext(input, index, '('))
          {
              tmp.child = expandNodes(input, ref index);
          }
          res.Add(tmp);
      }
  
  
      return res;
  }
  
  
  private bool checkNext(string s, int index, char desiredChar)
  {
      string vc = "" + s[index];
      while (index &lt; s.Length &amp;&amp; !char.IsLetterOrDigit(s[index]))
      {
          char chr = s[index];
          if (chr == desiredChar)
          {
              return true;
          }
          index++;
      }
      return false;
  }
  
  
  private string findToken(string s, ref int index)
  {
      string res = null;
      while (!char.IsLetterOrDigit(s[index++]) &amp;&amp; index &lt; s.Length) ;
      index--;
  
      while (index &lt; s.Length &amp;&amp; char.IsLetterOrDigit(s[index]))
      {
          res += s[index];
          index++;
      }
      return res;
  }
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/5j38O.png" alt="enter image description here"></p>