I have to list the number of documents related to items in a hierarchical tree.
The specification states: The tree will only ever be 2 levels deep. The higher level items will list not only the number of documents in it's folder, but also the total count of documents in the child folders. They want this total to include the documents in the current folder.
I've developed the solution below, it works, however it just seems complicated, hard to maintain and probably not the most efficient way to do this. Also, if the tree is ever more than 2 levels deep, this will fail.
class Item
{
public int Id { get; set; }
public int ParentId { get; set; }
public int DocumentCount { get; set; }
public int ChildItemCount { get; set; }
public int ChildCount { get; set; }
}
static class Program
{
static void Main()
{
var items = new List<Item>
{
new Item {Id = 1, ParentId = 0},
new Item {Id = 2, ParentId = 1},
new Item {Id = 3, ParentId = 1},
new Item {Id = 4, ParentId = 2},
new Item {Id = 5, ParentId = 2},
new Item {Id = 6, ParentId = 3},
new Item {Id = 7, ParentId = 3},
new Item {Id = 8, ParentId = 3}
};
// setup
var rnd = new Random();
items.ForEach(c => c.DocumentCount = rnd.Next(1, 10));
// act
items.ForEach(z => z.ChildCount = items.Count(x => x.ParentId == z.Id));
items.ForEach(z => z.ChildItemCount = items.Where(x => x.ParentId == z.Id).Sum(y => y.DocumentCount) + z.DocumentCount);
items.Where(k => k.ParentId == 0).ToList().ForEach(z => z.ChildItemCount = items.Where(x => x.ParentId == z.Id).Sum(y => y.ChildItemCount) + z.DocumentCount);
// output
items.ForEach(i => Console.WriteLine("Id: {0}, ParentId: {1}, DocumentCount: {2}, ChildCount: {3}, ChildItemCount: {4}", i.Id, i.ParentId, i.DocumentCount,i.ChildCount, i.ChildItemCount));
Console.ReadKey();
}
}
This gives the output below which is technically correct and meets the spec, but I just feel the solution is not the best solution. Can anyone think of a better way to do this?
Id: 1, ParentId: 0, DocumentCount: 8, ChildCount: 2, ChildItemCount: 46
Id: 2, ParentId: 1, DocumentCount: 7, ChildCount: 2, ChildItemCount: 16
Id: 3, ParentId: 1, DocumentCount: 8, ChildCount: 3, ChildItemCount: 22
Id: 4, ParentId: 2, DocumentCount: 2, ChildCount: 0, ChildItemCount: 2
Id: 5, ParentId: 2, DocumentCount: 7, ChildCount: 0, ChildItemCount: 7
Id: 6, ParentId: 3, DocumentCount: 9, ChildCount: 0, ChildItemCount: 9
Id: 7, ParentId: 3, DocumentCount: 1, ChildCount: 0, ChildItemCount: 1
Id: 8, ParentId: 3, DocumentCount: 4, ChildCount: 0, ChildItemCount: 4