首页 > 解决方案 > 保持原始列表不变

问题描述

在我的以下代码中,myOriginalList 仍在进行修改。如何保持不变?

谢谢你的帮助。

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; 
        }  

标签: c#genericscollections

解决方案


您需要创建列表的深层副本。一种可能的方法是克隆每个 Product 对象。

在 Product 类中添加一个具有类似功能的静态 Clone 方法。

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

现在,遍历列表,克隆并将每个元素添加到新列表中。

var newList = new List<Product>();
oldList.ForEach(x => newList.Add(x.Clone()));

推荐阅读