2017-12-06 1 views
-2

루프의 계층 적 목록에서 하위 항목의 값을 합계하는 방법.루프의 계층 적 목록에서 하위 항목의 값을 합하는 방법

목록의 루프 중에 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) 
      { 

      } 
     } 
    } 
} 
+3

"재귀 적 방법을 사용했지만 시도 할 수 없었습니다."게시물을 올리십시오. * 시도한 것을 * 시도하십시오. 최악의 경우 여기 누군가가 똑같은 해결책을 씁니다. 왜냐하면 우리는 당신이 이미 시도한 것을 알지 못하기 때문입니다. 그러나 이것이 당신을 도울 것이라고 의심합니다. 그렇지 않습니까? – HimBromBeere

+1

시도해 보셨습니까? – Alejandro

+0

시험이나 저주 등의 질문입니까? – KinSlayerUY

답변

0

들이 귀하의 예제에있는 방법을 분류되어,이 작업을 수행하는 가장 빠른 방법은 역순으로 목록을 반복하고 올바른 사용하여 목록 항목에 금액을 추가하는 것 신분증.

  1. 으로 반복 뒤로 목록을
  2. 현재 요소는 부모가 * 가격이

편집 할 수있는 금액과 금액을 추가가있는 경우 : 소스로 의견을 읽은 후

, 나는 당신이 이미 내가 쓴 것을 알고 있다고 가정합니다.

내 접근 방식은 다음과 같습니다 계층 구조를 만들기위한

 for (int i = myList.Count - 1; i > 1; i--) 
     { 
      var temp = myList.ElementAt(i); 
      if (temp.parentId != null) 
      { 
       var parent = myList.ElementAt(temp.parentId - 1); 
       parent.amount += temp.amount; 
       parent.price += (temp.amount * temp.price); 
      } 
     } 
0

을, 나는 부모와 자녀 모두 회원을 가지고, 트리 노드의 종류를 닮은 당신의 PlanilhaCusto 수정에 대한 트래버스을 완화

이 구조와 초기 입력이 주어
public class PlanilhaCusto 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public int? ParentId { get; set; } 
    public decimal Amount { get; set; } 
    public decimal Price { get; set; } 
    public IEnumerable<PlanilhaCusto> Children { get; set; } 
} 

enter image description here

,

는 상관없이 일부 재귀 거기에 의존 얼마나 많은 수준의 전체 트리 구조를 구축 할 수 있습니다 비슷한에 초기 데이터 소스를 투사 할

public IEnumerable<PlanilhaCusto> Descendants(PlanilhaCusto parent, IEnumerable<PlanilhaCusto> source) 
{ 
    var query = from node in source 
       where node.ParentId == parent.Id 
       let children = Descendants(node, source) 
       select new PlanilhaCusto 
       { 
        Id = node.Id, 
        ParentId = node.ParentId, 
        Name = node.Name, 
        Amount = node.Amount, 
        Price = node.Price, 
        Children = children, 
       }; 

    return query.ToList(); 
} 

var hierarchy = from node in source 
       let children = Descendants(node, source) 
       where node.ParentId == null 
       select new PlanilhaCusto 
       { 
        Id = node.Id, 
        ParentId = node.ParentId, 
        Name = node.Name, 
        Price = node.Price, 
        Children = children, 
       }; 
enter image description here

여기에서

계층 구조를 탐색하고 총 가격을 구성하면됩니다.

public decimal? Total(PlanilhaCusto node) 
{ 
    decimal? price = node.Price * node.Amount; 
    if (node.Children != null) 
    { 
     foreach (var child in node.Children) 
     { 
      price += Total(child); 
     } 
    } 

    return price; 
} 

var totals = from node in hierarchy 
      select new 
      { 
       Id = node.Id, 
       Name = node.Name, 
       Total = Total(node), 
      }; 

enter image description here

+0

전체 구현에 대한 관련 요지보기 https://gist.github.com/dandohotaru/f87a4adf21b8e516cabf67ecfd4674e8 –

관련 문제