c# - 保持原始列表不变
问题描述
在我的以下代码中,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;
}
解决方案
您需要创建列表的深层副本。一种可能的方法是克隆每个 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()));
推荐阅读
- assembly - 如何使计时器起作用?启动后 5 秒调用 int 4ah
- python - 循环numpy数组v/s映射函数?
- angular - 多点触控在 Chrome 中不起作用
- python - 我怎样才能得到百分比?
- ios - 自从向文本添加语音(语音识别)以来,文本到语音的音量显着下降
- python - 使用 Bootstrap 渲染 SelectFields 的 WTF 字段列表
- sql-server - 两列之一上的唯一外键
- arrays - Swift:遍历一个数组并逐项显示屏幕上的信息(屏幕更新)
- javascript - 如何使用自定义接口扩展 firebase.User 或将自定义值传递给 angularfire2 中的 firebase 集合?
- oracle - 在 oracle db 中创建了更多会话