Harris Stephanie Harris Stephanie - 4 months ago 28
C# Question

Use recursion to get parent value and children value and all its children's children value

Need help with the following question. I was tested on this and failed and really want to know the answer so that I can study it....

Assume an list (C#) of objects in pyramid structure with the following properties:


  • id

  • name

  • value

  • parentid



Example (C#):

var b = new block();
b.id = 100;
b.name = "block 100"
b.value = 102.50;
b.parentid = 99;


Write a recursive function that accepts an ID as the only parameter and will loop through an array or list of an undetermined size and number of levels. The recursive function will calculate




block block1 = new block(1, null, "block 1", 11.34M);
block block11 = new block(11, 1, "block 11", 234.34M);
block block111 = new block(111, 11, "block 111", 111);
block block12 = new block(12, 1, "block 12", 564);
block block13 = new block (13, 1, "block 13", 342.23M);
block block131 = new block(131, 13, "block 131", 945);
block block132 = new block(132, 13, "block 132", 10M);
block block133 = new block(133, 13, "block 133", 88M);
block block1331 = new block(1331, 133, "block 1331", 45);

block block2 = new block(2, null, "block 2", 234);
block block3 = new block(3, null, "block 3", 1249.34M);

blocks = new List<block>();
blocks.Add(block1);
blocks.Add(block11);
blocks.Add(block111);
blocks.Add(block12);
blocks.Add(block13);
blocks.Add(block131);
blocks.Add(block132);
blocks.Add(block133);
blocks.Add(block1331);
blocks.Add(block2);
blocks.Add(block3);

decimal sum = SumAll(1);
Console.WriteLine(sum);
Console.ReadKey();
}





I need a function that gives me a total "value" from the "value" property for the parent and all of its children and its children's children. Can anyone help?

Answer

To get you moving (and hopefully editing your question with what you've tried so far), you want something like this:

// defined at class level/scope outside method
private List<block> blocks;

...

private int SumAll(int id) {
      var initialBlock = blocks.FirstOrDefault(b => b.id == id);
      int value = initialBlock.Value;

      var childBlocks = blocks.Where(b => b.parentId = id).ToList();
      foreach (var childBlock in childBlocks) {
            value += SumAll(childBlock.id);
      }

      return value;
}