Get hierarchy from flat datatable using linq extension methods

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

Hi I have dataTable which contains the following information:

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

I need to get hierarchy using extension methods (Select and GroupBy).

Something like this.

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

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


Answers

    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 }
                                )
                            }
                        )
                }
            );
    }

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/13745556/get-hierarchy-from-flat-datatable-using-linq-extension-methods

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils