this is my question: Let's say I have a block class, and a list of blocks:
List<Block> blocks = new List<Block> ();
Block b1 = new Block ();
b1.id_material = 1;
b1.id_color = 1;
b1.weight = 1.5f;
Block b2 = new Block();
b2.id_material = 2;
b2.id_color = 1;
b2.weight = 3f;
Block b3 = new Block();
b3.id_material = 1;
b3.id_color = 1;
b3.weight = 4.5f;
blocks.Add (b1);
blocks.Add (b2);
blocks.Add (b3);
class Block
{
public int id_material { get; set; }
public int id_color { get; set; }
public float weight { get; set; }
}
As you can see each block has its material, color and weigth. I need to create a new list, where if two or more blocks have the same color and material, it must sum their weights.
In this example, the new list should have two blocks,liko so:
List<Block> new_blocks = new List<Block> ();
Block b1 = new Block ();
b1.id_material = 1;
b1.id_color = 1;
b1.weight = 6f; //1,5 4,5
Block b2 = new Block();
b2.id_material = 2;
b2.id_color = 1;
b2.weight = 3f;
new_blocks.Add(b1);
new_blocks.Add(b2);
Is there a way I can do that ? Thanks!
CodePudding user response:
This can be done using GroupBy
using the namespace System.Linq
like :
var new_blocks = blocks.GroupBy(x=>
new
{
x.id_material ,
x.id_color
}
)
.Select(x => new Block()
{
id_material = x.Key.id_material,
id_color = x.Key.id_color,
weight = x.Sum(y => y.weight)
}).ToList();
So we had grouped the blocks based on the id_material
and color
and then we sum the weight of all the blocks that have same id_material
and color
Output:
id_material:1,id_color:1,weight:6
id_material:2,id_color:1,weight:3
For reference see the working DEMO Fiddle here