1

嗨,我有 dataTable,其中包含以下信息:

A1 B1 C1
A1 B1 C2
A1 B2 C3
A1 B2 C4
A2 B1 C5
A2 B1 C6
A2 B3 C7

我需要使用扩展方法(Select 和 GroupBy)来获取层次结构。

像这样的东西。

A1
|_ B1
| |_ C1
| |_ C2
|
|_ B2
   |
   |_ C3
   |_ C4

A2
|_ B1
| |_ C5
| |_ C6
|
|_ B3
    |_ C7


4

1 回答 1

0
    public class Node
    {
        public string Value { get; set; }
        public IEnumerable<Node> Children { get; set; }
    }

    public IEnumerable<Node> BuildHierarchy(IEnumerable<Entry> entries)
    {
        return entries.GroupBy(entry => entry.A)
            .Select(grouping => 
                new Node 
                { 
                    Value = grouping.Key,
                    Children = grouping.GroupBy(entry => entry.B)
                        .Select(grouping2 => 
                            new Node
                            { 
                                Value = grouping2.Key,
                                Children = grouping2.Select(entry => 
                                    new Node { Value = entry.C }
                                )
                            }
                        )
                }
            );
    }
于 2013-05-08T23:08:12.213 回答