.net - 将扁平化数据源转换为分层数据源

标签 .net algorithm .net-3.5 datasource hierarchy

假设我有一个表,例如:

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 的 child ,C 是 B 的 child ,依此类推。

我怎样才能将表顶部变成分层数据源? 比如

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

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

最佳答案

您可以编写一个简单的迭代来遍历文件并将元素对添加到字典中。在看起来像 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

希望对您有所帮助。

关于.net - 将扁平化数据源转换为分层数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4467141/

相关文章:

c# - Func<T> Inkover 错误无法从用法中推断出来。尝试明确指定类型参数

c# - MyApp.vshost.exe 应该与 MyApp.exe 一起分发吗?

php - PHP 中的目标搜索功能

java - 这是一个 "good enough"随机算法吗?如果它更快,为什么不使用它?

c# - InvalidCastException Dictionary<string, string> 使用 Exception.Data

asp.net - 在 Linq-to-SQL 中使用 WHERE 子句时出错

algorithm - 比较两个列表的顺序

c# - 使用 LINQ 按内部 Dictionary 值的值对 Dictionary<string,Dictionary<string,string>> 进行排序?

c# - Linq:Xml 到 IEnumerable<KeyValuePair<int, string>> 延迟执行?

c# - 打印包含所有行和所有列的 datagridview 的最佳方法?