Let's say I have a table such as:
D_ID C_ID B_ID A_ID
1D 1C 1B 1A
4D 2C 6B 1A
6D 1C 1B 1A
9D 开发者_如何学JAVA 1C 1B 1A
8D 2C 6B 1A
And let's say that structurally speaking, I know the following:
A's
B's
C's
D's
That is D's are children of C's, C's of B's and so on.
How could I turn the table up top into a hierarchical data source? Such as
ID ParentID
1D 1C
4D 2C
6D 1C
9D 1C
8D 2C
1C 1B
2C 6B
1B 1A
6B 1A
1A Null
This could then serve as a hierarchical datasource for a Telerik TreeView or other hierarchical controls? I know I could iterate over every item and build it myself, but I am wondering if there are better known ways to iterate this. Perhaps even a built in way to achieve this.
You could write a simple iteration passing through the file and adding pairs of elements to a dictionary. In pythonish looking psuedo code:
// open the file you want to parse.
file = open(my_log_file)
// create a hash map from ID to parent.
dictionary = {}
// read through the file line by line
for line in file.getlines():
// ignore first line ...
// read the 4 columns in each line
columns[] = line.split(" ")
// add pairs (id=column[i], parent=column[i+1]) to the hashmap
dictionary[column[1]] = column[2]
dictionary[column[2]] = column[3]
dictionary[column[3]] = column[4]
dictionary[column[4]] = Nil
// output the hashmap line by line.
print "ID", "Parent ID"
for (id, parent) in dictionary:
print id, parent
I hope this helps.
Here is a quick thought....
If I understand this correctly you can just iterate across the list from right to left, and read pairs... Use a dictionary/map/hashtable to keep them organized. You may need to define a custom comparator for it but thats not too hard.
So as you iterate along from right to left, top to bottom, you add the pairs as you read them so..
parent = "1A";
child = "1B";
list.add(child, parent);
//Then on the next iteration.....
parent = "1B";
child = "1C";
And so on you go...
This way using the child as the key, you are left with a list of all the unique values, this becomes your ID column.
Then your list.values() becomes your ParentID column since it will contain the duplicates for all of the parents that had more than one child. This is also why the child works perfectly as the key since you can only be born once, but you can have many children.
EDIT: BAH! Someone beat me to it with a much more complete version of what I was proposing anyway... oh well. I like my verbal description better ;)
精彩评论