0

I am trying to create a hierarchy from excel file. The sample data as follows:

Path    Description
1            a
1.1          b
1.1.1        c
1.2          d
1.3          e

Now, I need to read each cell and check if it has child or not,

the output must be as,

Path           Description
1              a
 1.1           b
  1.1.1        c
 1.2           d
 1.3           e

How can I achieve this using C# and print it on console? Please Help me.

user5928466
  • 81
  • 1
  • 1
  • 8
  • Check this question which is also answered. http://stackoverflow.com/questions/18316902/building-a-tree-with-parent-child-relationship-using-c-sharp-recursively – Kamil Ibadov Jan 16 '17 at 10:58
  • @KamilIbadov The issue I am facing is how can I check for Dots(.) every time and create tree like structure. – user5928466 Jan 16 '17 at 11:02
  • For each cell, you can get a count of dots using something like `var dotCount = cellValue.length - cellValue.replace(".", "");` or `var dotCount = cellValue.split('.').length;`. – Serge Jan 16 '17 at 11:09
  • See this for counting occurrences of character in string : http://stackoverflow.com/questions/541954/how-would-you-count-occurrences-of-a-string-within-a-string – PaulF Jan 16 '17 at 11:16

1 Answers1

0

I suspect you're wanting something else, but your question in answered with the following code:

var source = @"Path    Description
1            a
1.1          b
1.1.1        c
1.2          d
1.3          e";

var lines =
    source
        .Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
        .Select(x => x.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries));

var results =
    lines
        .Skip(1)
        .Select(x => new
        {
            Indent = x[0].Count(y => y == '.'),
            Path = x[0],
            Description = x[1]
        })
        .Select(x =>
            String.Format(
                "{0}{1}{2}{3}",
                "".PadLeft(x.Indent + 1).Substring(1),
                x.Path,
                "".PadLeft(15 - x.Path.Length - x.Indent),
                x.Description));

Console.WriteLine(String.Join(Environment.NewLine, results));

It gives:

1              a
 1.1           b
  1.1.1        c
 1.2           d
 1.3           e
Enigmativity
  • 113,464
  • 11
  • 89
  • 172