【问题标题】:Turn a flattened datasource into a hierarchical one将扁平数据源转换为分层数据源
【发布时间】:2011-05-26 21:53:47
【问题描述】:

假设我有一张桌子,例如:

D_ID    C_ID    B_ID    A_ID
1D      1C      1B      1A
4D      2C      6B      1A
6D      1C      1B      1A
9D      1C      1B      1A
8D      2C      6B      1A

假设从结构上讲,我知道以下内容:

A's
 B's
  C's
   D's

也就是说 D 是 C 的孩子,C 是 B 的孩子等等。

如何将表格顶部变成分层数据源? 比如

ID ParentID
1D  1C
4D  2C
6D  1C
9D  1C
8D  2C
1C  1B
2C  6B
1B  1A
6B  1A
1A  Null

这可以作为 Telerik TreeView 或其他分层控件的分层数据源吗? 我知道我可以迭代每个项目并自己构建它,但我想知道是否有更好的方法来迭代它。甚至可能是实现这一目标的内置方法。

【问题讨论】:

    标签: .net algorithm .net-3.5 datasource hierarchy


    【解决方案1】:

    您可以编写一个简单的遍历文件并将元素对添加到字典中。在看起来像 Python 的伪代码中:

    // 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
    

    我希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      这是一个快速的想法......

      如果我理解正确,您可以从右到左遍历列表,然后读取对...使用字典/地图/哈希表使它们井井有条。您可能需要为它定义一个自定义比较器,但这并不难。

      因此,当您从右到左、从上到下进行迭代时,您可以在阅读时添加对......

      parent = "1A";
      child = "1B";
      list.add(child, parent);
      //Then on the next iteration.....
      parent = "1B";
      child = "1C";
      

      等你去...

      这样使用孩子作为键,你会得到一个所有唯一值的列表,这将成为你的 ID 列。

      然后您的 list.values() 将成为您的 ParentID 列,因为它将包含所有拥有多个孩子的父母的重复项。这也是为什么孩子可以完美发挥关键作用,因为你只能出生一次,但你可以生很多孩子。

      编辑:呸!无论如何,有人用我提议的更完整版本击败了我……哦,好吧。我更喜欢我的口头描述;)

      【讨论】:

        猜你喜欢
        • 2013-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-16
        • 2022-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多