tags:

views:

30

answers:

2

Hello

What would be the best way to duplicate an object placed in a list of items and change a property of duplicated objects ?

I thought proceed in the following manner: - get object in the list by "ref" + "article" - Cloned the found object as many times as desired (n times) - Remove the object found - Add the clones in the list

What do you think?

A concrete example:

Private List<Product> listProduct;
listProduct= new List<Product>();

Product objProduit_1 = new Produit;

objProduct_1.ref = "001";
objProduct_1.article = "G900";
objProduct_1.quantity = 30;

listProducts.Add(objProduct_1);

ProductobjProduit_2 = new Product;

objProduct_2.ref = "002";
objProduct_2.article = "G900";
objProduct_2.quantity = 35;

listProduits.Add(objProduct_2);

desired method:

public void updateProductsList(List<Product> paramListProducts,Produit  objProductToUpdate, int32 nbrDuplication, int32 newQuantity){       
...      
}

Calling method example:

 updateProductsList(listProducts,objProduct_1,2,15);

Waiting result:

Replace follow object :

ref = "001";
article = "G900";
quantite = 30;

By:

ref = "001";
article = "G900";
quantite = 15;

ref = "001";
article = "G900";
quantite = 15;

The Algorithm is correct? Would you have an idea of the method implementation "updateProductsList"

Thank you in advance for your help.

A: 

First, it looks like you want to implement your own ProductList object. The implementation is simple, when extending List<Product>. Second, to update the product, you can remove the old product, clone it twice and add it twice.

public class ProductList : List<Product> {
    public void update(Product product, int nrOfDuplications, int newQuantity) {
       Remove(product);
       for(int i = 0; i < nrOfDuplications; i++) {
           Add(new Product() {
               ref = product.ref,
               article = product.article,
               quantity = newQuantity
           });
       }
    }
}

This could be further improved by using a copy constructor, which means that you don't need the complete list of all the parts.

Marc
thank you for your reply, I actually caught your solution. Just out of curiosity is there a pattern corresponding to my needs?Better than duplicate object for only one property to change.Thank you
A: 

thank you for all, this solution suits me very well, but is there not a way to clone the old product in other manner? because the product class has several properties, I was thinking something looking like this:

...
    Add(newProduct = Product.clone; 
        newProduct.quantity = newQuantity;
               });