我有一个接收ID的List。它在foreach语句之外被实例化。
List<int> indices = new List<int>();
foreach (var m in docsRelacionadosModel)
{
//.. do stuff
modelTemp.indices = indices;
//..here I do more stuff and some time it goes to the next iteration and I need to keep the value in indices to get more values.
//although in a condition
if(isOk) {
//I save the value of this list to a model
model.indices = modelTemp.indices;
//And I need to clear the list to get new values
indices.Clear(); <--- This will clear the values saved in model.indices
}
}
由于它具有通过引用传递的值,如何将值保留在model.indices中?
答案 0 :(得分:2)
您需要复制列表并将副本保存到model.indecies
。虽然有许多方法可以复制列表,但LINQ ToList
扩展方法可能是最方便的:
model.indices = modelTemp.indices.ToList();
另一种选择是使用List
构造函数:
model.indices = new List<int>(modelTemp.indices);
答案 1 :(得分:0)
只需创建列表的副本:
model.indices = new List<int>(modelTemp.indices);
答案 2 :(得分:0)
根据this S/O question,最简单的方法是在列表中调用ToList:
model.indices = modelTemp.indices.ToList();
您还可以将实例化为新列表,将列表作为构造函数参数传递。