Harris Stephanie Harris Stephanie - 1 year ago 122
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>();

decimal sum = SumAll(1);

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 Source

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;