Sunday, February 5, 2012

C# Partial in-code implementation of the Start With, Connect By clause

Wednesday, May 20, 2009, 13:28
This news item was posted in Technology category and has 0 Comments so far.

I am working on this project where I had a list of parent - child elements and I had to extract a particular chain of parent - child elements, given the starting child. I am sure lot of developers have written this code. As a natural instinct I started googling for an in-code implementation of Oracle’s START WITH, CONNECT BY clause.

After spending some time searching this, I got nothing. So I implemented this code and thought I will share this out for anyone who is looking for it. This code doesn’t do well with duplicate relationships, so if that is something you want, you are on your own.

initialLink is the initial List.

startingChild is the starting child that you want to start traversing the parent - child link.

extractedLink is the resulting link.

void ExtractParentChild( Dictionary<string, string> initialLink, string startingChild,
Dictionary<string, string> extractedLink )
{
// Traverse the Dictionary to build the parent-child dictionary
foreach (var v in initialLink)
{

if (v.Key.Equals(startingChild))
{
extractedLink.Add(v.Key, v.Value)
ExtractParentChild(initialLink, v.Value, extractedLink);
}// if
} // foreach
}

If you need to stop somewhere before the end of the link is reached you can add the condition around the for loop and return in the if, when the condition is reached.

Responses are currently closed, but you can trackback from your own site.

website design quote