【发布时间】:2018-05-20 09:25:36
【问题描述】:
如何在循环中对分层列表中的子项的值求和。
我需要在列表中的循环过程中,amount 和 price 属性的值包含子项的这些属性的总和。
以下是用于帮助我解决问题的两个类。
namespace SGP.Dto.Custo
{
public class PlanilhaCusto
{
public int id{ get; set; }
public int parenteId{ get; set; }
public string name { get; set; }
public decimal amount{ get; set; }
public decimal price{ get; set; }
public PlanilhaCusto(int pId, int pParenteId, pName, decimal pAmount, decimal pPrice)
{
id = pId;
parentId = pParentId;
name = pName;
amount = pAmount;
price = pPrice;
}
}
}
namespace SGP.Dto.Custo
{
public class ShowList
{
List<Dto.Custo.PlanilhaCusto> myList = new List<PlanilhaCusto>();
public void Show()
{
myList.Add(new PlanilhaCusto(1, null, "Projetos", 0, 0));
myList.Add(new PlanilhaCusto(2, 1, "Arquitetura", 5,10));
myList.Add(new PlanilhaCusto(3, 1, "Estrutura", 0, 0));
myList.Add(new PlanilhaCusto(4, 3, "Civil", 1, 50));
myList.Add(new PlanilhaCusto(5, 3, "Infra", 3, 75));
myList.Add(new PlanilhaCusto(6, null, "Pessoal", 0, 0));
myList.Add(new PlanilhaCusto(7, 6, "Mão de Obra", 20, 5700));
/*In this loop the value of the parent items must be updated
(calculated). The hierarchy of the list can be unlimited,
like a tree. I tried using a recursive method but I could
not do it.*/
foreach (var itemList in myList)
{
}
}
}
}
【问题讨论】:
-
“我尝试使用递归方法,但我做不到”请发布您尝试过的什么。在最坏的情况下,这里有人会编写完全相同的解决方案,因为我们不知道您已经尝试过什么。但是我怀疑这会对您有所帮助,不是吗?
-
你有没有尝试过?
-
这是来自测试或诅咒之类的问题吗?
标签: c# list linq recursion hierarchical