Search code examples
c#recursiontree

Build a tree from dot-delimited hierarchical numbers


I have a list of strings representing hierarchical numbers in ascending order, with a maximum depth of 2 levels. Each number is delimited by dots (.), with the first segment representing the root, the second segment representing the first level, and the third representing the second level.

The numbers are formatted like so:

02 (root)
02.00 (first level)
02.00.00 (second level)

I want to organize these numbers into a nested hierarchy structure where each number is grouped under its parent level. For example, 02 would be the root, 02.00 would be a child of 02, and 02.00.00 would be a child of 02.00.

Here is the link to see the data: KLE-Online


Solution

  • I would do it like this :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.txt";
            static void Main(string[] args)
            {
                string[] lines = File.ReadAllLines(FILENAME);
                List<ParagraphTitles> titles = lines.Select(x => new ParagraphTitles(x)).ToList();
    
                List<ParagraphTitles> sortedTitles = titles.OrderBy(x => x).ToList();
    
                ParagraphTitles root = new ParagraphTitles();
                root.CreateTree(sortedTitles, 0);
    
    
            }
        }
        public class ParagraphTitles : IComparable<ParagraphTitles>
        {
            public int[] paragraphs { get; set; }
            public string sParagraphs { get; set; }
            public string text { get; set; }
            public List<ParagraphTitles> chapters { get; set; }
    
            public ParagraphTitles() { }
            public ParagraphTitles(string line)
            {
                int firstSpace = line.IndexOf(' ');
                sParagraphs = line.Substring(0, firstSpace);
                paragraphs = line.Substring(0, firstSpace).Trim().Split(new char[] { '.' }).Select(x => int.Parse(x)).ToArray();
                text = line.Substring(firstSpace + 1);
            }
            public int CompareTo(ParagraphTitles other)
            {
                int minSize = Math.Min(paragraphs.Length, other.paragraphs.Length);
    
                for (int i = 0; i < minSize; i++)
                {
                    if (paragraphs[i] != other.paragraphs[i])
                    {
                        return paragraphs[i].CompareTo(other.paragraphs[i]);
                    }
                }
    
                return paragraphs.Length.CompareTo(other.paragraphs.Length);
            }
            public void CreateTree(List<ParagraphTitles> chapters, int level)
            {
                var groups = chapters.GroupBy(x => x.paragraphs[level]).ToList();
    
                foreach (var group in groups)
                {
                    List<ParagraphTitles> orderedChapters = group.OrderBy(x => x.paragraphs.Length).ToList();
                    if (this.chapters == null) this.chapters = new List<ParagraphTitles>();
                    this.chapters.Add(orderedChapters.First());
                    orderedChapters.First().CreateTree(orderedChapters.Skip(1).ToList(), level + 1);
                }
            }
    
        }
    }
    

    here is a sample of the file

    00 The municipality's board Service text
    00.01 The municipality's board Keywords Keywords
    00.03 International business and the EU Service text Keywords Keywords
    00.05 Visits, representation, etc. Keywords Keywords
    00.06 Administration of foundations, grants and foundations Legal references Service text Keywords Keywords
    00.07 Management principles Legal references Service text Keywords Keywords
    00.13 Communication and information services Service text Keywords Keywords
    00.14 Citizen Service Keywords Keywords
    00.15 Administrative organization Service text Keywords Keywords
    00.16 Experimental and development work Service text Keywords Keywords
    00.17 Municipal / cross-sectoral cooperation Service text Keywords Keywords
    00.18 Task and structural changes in municipalities, overall activities Legal references Service text Keywords Keywords
    00.20 History of the municipality / institution, weapons, etc. Keywords Keywords
    00.20.00 History of the municipality / institution, weapons, etc. in general [B] Legal references Service text Keywords Keywords
    00.20.05 Naming of institutions, schools, etc. [B] Service text Keywords Keywords
    00.22 The municipal council, committees, etc. - the municipality's board Service text Keywords Keywords
    00.24 Municipal associations, associations, etc. Keywords Keywords
    00.30 Budget - the municipality's financial management Legal references Service text Keywords Keywords
    00.32 Accounting - the municipality's financial management Legal references Service text Keywords Keywords
    00.34 Loans and borrowing - the municipality's financial management Legal references Service text Keywords Keywords
    00.36 Mortgage deeds, bonds and shares Keywords Keywords
    01 Spatial planning and nature conservation Service text
    01.00 Physical planning and nature protection Keywords Keywords
    01.01 National Planning Directives, etc. and regional development planning Service text Keywords Keywords
    01.02 Municipal planning and local planning Service text Keywords Keywords
    01.03 Zoning and land zone administration Legal references Service text Keywords Keywords
    01.04 Subdivision conditions and other cadastral conditions Keywords Keywords
    01.05 Nature conservation Legal references Service text Keywords Keywords
    01.06 Geographical information systems Keywords Keywords
    01.07 Holiday home areas Keywords Keywords
    01.09 Raw material extraction Service text Keywords Keywords
    01.10 Building protection and building preservation Keywords Keywords
    01.11 Urban renewal and urban development Legal references Keywords Keywords
    01.12 Allotment garden areas Keywords Keywords
    01.13 Operation of agricultural land Legal references Keywords Keywords
    01.15 Land distribution Service text Keywords Keywords
    01.16 Assessment of Impacts on the Environment (EIA) [deleted] Legal references Service text Keywords Keywords
    01.24 Coastal protection Legal references Service text Keywords Keywords
    02 Byggeri
    02.00 Construction Legal references Service text Keywords Keywords
    02.01 Land use for development Legal references Keywords Keywords
    02.02 The height and distance conditions of the buildings Legal references Keywords Keywords
    02.03 Interior design of buildings Legal references Service text Keywords Keywords
    02.04 Constructive provisions Keywords Keywords
    02.05 Fire conditions Legal references Service text Keywords Keywords
    02.08 Installations etc. Legal references Keywords Keywords
    02.25 Fire protection measures for chimneys and fireplaces Legal references Keywords Keywords
    02.34 Building permit and notification of construction work Legal references Keywords Keywords
    03 Boliger
    03.00 Boliger Stikord Stikord
    03.01 Benyttelse af boliger Lovhenvisninger Servicetekst Stikord Stikord
    03.02 Almene boliger, nybyggeri og renovering Lovhenvisninger Servicetekst Stikord Stikord
    03.03 Private andelsboliger Lovhenvisninger Servicetekst Stikord Stikord
    03.08 Drift, tilsyn og støtte til selvejende ungdomsboliger Lovhenvisninger Stikord Stikord
    03.09 Lejeforhold mv. i private boliger Lovhenvisninger Servicetekst Stikord Stikord
    03.10 Drift af og tilsyn med almene boliger (ikke-økonomisk) Lovhenvisninger Servicetekst Stikord Stikord
    03.11 Økonomisk tilsyn med almene boliger Lovhenvisninger Servicetekst Stikord Stikord
    03.12 Almene boliger - tvister mellem lejer og udlejer Lovhenvisninger Servicetekst Stikord Stikord
    03.14 Støttede private ungdomsboliger Lovhenvisninger Servicetekst Stikord Stikord
    03.16 Energibesparende foranstaltninger i pensionisters boliger [udgår 2021] Servicetekst Stikord Stikord
    03.17 Statstilskud til omstilling af ældre boliger til kraftvarme [udgår 2021] Servicetekst Stikord Stikord
    03.18 Statstilskud til omstilling af elopvarmede bygninger [udgår 2021] Servicetekst Stikord Stikord
    03.22 Friplejeboliger Servicetekst Stikord Stikord
    03.25 Boligplacering af flygtninge Lovhenvisninger Servicetekst Stikord Stikord
    03.30 Landsbyggefondens årlige ramme til boligsocial indsats Lovhenvisninger Stikord Stikord