Stories from a Job Interview: Part 1

time to read 3 min | 488 words

In a job interview I was asked to pull a list of records from a database and save them to XML. The data was hierarchical in nature, of course. The code I produce looked a bit like this:

 

Dictionary<int, XmlNode> connections = new Dictionary<int, XmlNode>();

XmlDocument xdoc = new XmlDocument();

XmlNode root = xdoc.CreateRootNode("Names");   

       

using(IDbConnection con = GetConnection())

{

      using(IDbCommand command = con.CreateCommand())

      {

            command.CommandText = "select id, parent id, name from Foo order by parent id;"

            IDataReader reader = command.ExecuteReader();

            while(reader.Read())

            {

                  int id = reader.GetInt(0);

            int parent = reader.GetInt(1);

            string name = reader.GetString(2);          

     

            XmlNode node;

            if(parent == 0)

                node = root.CreateChild("Name");

            else

                node = connections[parent].CreateChild("Name");

             

                  node.Text = name;

            node.Attributes.Add("id", id.ToString());

           

            connections.Add(id, node);

            }

      }

}

       

xdoc.Save("results.xml");

 

I believe that the purpose was to check if I know how to use recursion, but it never occurred to me to use it in a case like this. The code above uses a single database query and a single pass on the dictionary. It is, I believe, as efficient as you can get without really trying. The funny thing was that the interviewers tried to get me to use recursion (without saying it), but I literally couldn't understand what they meant until they said it.