Thursday, October 07, 2004

Recursion Alternative; or Non-Recursive Recursion Part II

I'm posting the code to my non-recursive recursion sample. I've made one minor stylistic change, by using a "while loop" instead of a "for loop". This example gets all decendant categories of a multi-generation category tree. It returns an ArrayList of int's. I've taken this directly from the blog application I'm working on, so there's some irrelevant (to this example) code -- you'll have to ignore it.

I'm also using this post as a test of the very cool C# code formatting tool written by Jean-Claude Manoli. The formatting tool and the C# project code can be found here. To view the code more easily, copy it out of the scrolling widget below, and paste it into VS.NET.



public ArrayList GetAllDecendantCategories(int category_ID)
{
//initialize the counter
int i = 0;

// read the datasource property from the app.config file
this.appSettingsReader = new AppSettingsReader();
string connectionString = (string)appSettingsReader.GetValue("datasource", typeof(string));

//create an ArrayList to hold the category_ID's
ArrayList ar = new ArrayList();

//add the parent category ID
ar.Add(category_ID);

//opent the connection to the database
SqlConnection Connection = new SqlConnection(connectionString);

while (i < class="rem">//database logic...
string commandtext = "SELECT category_ID FROM Category WHERE category_parent = " + ar[i];
SqlCommand command = new SqlCommand(commandtext, Connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);

//create a datatable to hold the categories
DataTable dt = new DataTable("category");

//clear and fill the categories DataTable
try
{
dt.Clear();
adapter.Fill(dt);
}
catch (Exception ex)
{
string message = ex.Message;
}

//loop over the resultset and add the child elements to the ArrayList
foreach (DataRow dr in dt.Rows)
{
//make sure the parent element is not being added as a child element
if (Convert.ToInt32(ar[i]) != Convert.ToInt32(dr["category_ID"]))
{
ar.Add(dr["category_id"]);
}
}

//increment the counter
i++;
}
return ar;
}

No comments: