0

In my following code, myOriginalList is still getting modified. How do I keep it unchanged?

Thanks for your help.

List<Product> myOriginalList = GetList(); 
List<Product> customList= new List<Product>();

                        foreach (var productType in myProductTypeList )
                        {
                            var tempList = myOriginalList.ToList(); 
                            var result = GetModifiedCustomList(tempList, productType );
                            customList.AddRange(result);                                                                                    
                        }
.....
.....
 private List<Product> GetModifiedCustomList(List<Product> inplist, string productType)
        {
            List<Product> tmpList = new List<Product>(inplist); 

            if (tmpList?.Count > 0)
            {
                tmpList.ForEach(r => { if (r.ProductType == "NONE") { r.ProductType= productType; } }); 
            }
            return tmpList; 
        }  
Jimmy
  • 2,106
  • 12
  • 39
  • 53
  • Possible duplicate of [Pass List to method without modifying original list](https://stackoverflow.com/questions/7712842/pass-list-to-method-without-modifying-original-list) – Jerodev Apr 25 '18 at 09:36
  • I don't think that `myOriginalList.ToList()` is creating a new list; it's passing the same reference. Try changing it to `myOriginalList.Select(m => m).ToList()` or `new List(myOriginalList)`. It will create a new copy of myOriginalList. – user1672994 Apr 25 '18 at 09:36
  • Make a deep copy/ clone of the list – Skyuppercut Apr 25 '18 at 09:36
  • As I see the code, the old list is not modified, but the values in the list are modified, since you change the instance value from new list. – Julo Apr 25 '18 at 09:37
  • 1
    @jerodev no..it isn't. That is for value types where new List(_list) creates a new copy. For reference types, reference gets copied – Skyuppercut Apr 25 '18 at 09:38
  • Yes, it's not your list that is being modified, it's the objects in the list. – DavidG Apr 25 '18 at 09:43

2 Answers2

1

You'll need to create a deep copy of the list. One possible way is to clone each of the Product object.

Add a static Clone method in the Product class which does similar function.

 public static Product Clone(Product product)
        {
            return new Product
            {
                Underlying = product.Underlying
            };
        }

Now, Iterate through the list, clone and add each element to the new list.

var newList = new List<Product>();
oldList.ForEach(x => newList.Add(x.Clone()));
Skyuppercut
  • 332
  • 3
  • 14
0

try this var tempList = new List<Product>(myOriginalList.ToArray()); as it will create new copy