Group repeated items from a list and add their values C #

0

I have the following list:

List<String> datos = new List<string>();

In it I keep the following data:

  datos.Insert(0, nomMaterial); //Material1
  datos.Insert(1, "$" + costoMaterial);//500.00
  datos.Insert(2, areaCuadrada);//80m2
  datos.Insert(3, "$" + costoTotal);//40,000

  datos.Insert(0, nomMaterial);//Material2
  datos.Insert(1, "$" + costoMaterial);//200
  datos.Insert(2, areaCuadrada);//40m2
  datos.Insert(3, "$" + costoTotal);//8,000


  datos.Insert(0, nomMaterial);//Material1
  datos.Insert(1, "$" + costoMaterial);//500.00
  datos.Insert(2, areaCuadrada);//20m2
  datos.Insert(3, "$" + costoTotal);//10,000

  datos.Insert(0, nomMaterial);//Material2
  datos.Insert(1, "$" + costoMaterial);//200.00
  datos.Insert(2, areaCuadrada);//10m2
  datos.Insert(3, "$" + costoTotal);//2000

I would like that for each Material that is repeated the amounts to be added to group them and in the end to show a summary of both, example:

Material: Material1 Cost: 500 SumaArea = 100m2 TotalSum = 50,000

Material: Material2 Cost: 200 SumaArea = 50m2 TotalSum = 10,000

The cost of each material will always be the same, what interests me is to know how to group them to obtain the sum of their areas and the total price without having to show one by one, I hope it was clear, thank you very much.

    
asked by user110518 14.12.2018 в 02:00
source

1 answer

3

To achieve what you propose you should use classes and not a string list, something like being

public class Material {
   public string Nombre {get;set;}
   public decimal Costo {get;set;}
   public int Area {get;set;}

   public decimal Total { 
       get { return this.Costo * this.Area; }
   }

 }

The total is a read-only property where you perform the calculation

Then you add the items using

List<Material> lista = new List<Material>();
Material m1 = new Material(){
    Nombre = "Material1",
    Costo = 500,
    Area = 80
};
lista.Add(m1);

Material m2 = new Material(){
    Nombre = "Material2",
    Costo = 200,
    Area = 40
};
lista.Add(m1);

Using linq you can group

var result = from item in lista
              group item by item.Nombre into g
              select new Material() {
                 Nombre = g.Key,
                 Costo = g.Sum(x=> x.Costo),
                 Area = g.Sum(x=>x.Area)
              };

to show it you just iterate the result of the linq

foreach(var item in result){
   Console.WriteLine("Material:{0} SumaTotal:{1}", item.Material, item.Total)
} 

as you will see using classes everything is simpler

    
answered by 14.12.2018 в 11:16