![](/img/trans.png)
[英]How to assign multiple values from one Model into a List<T> in the ViewModel?
[英]How to keep values from a List<T> in a model after clearing the list?
我有一個接收ID的列表。 它在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中?
您需要復制列表並將該副本保存到model.indecies
。 雖然有許多方法可以復制列表,但LINQ ToList
擴展方法可能是最方便的:
model.indices = modelTemp.indices.ToList();
另一種選擇是使用List
構造函數:
model.indices = new List<int>(modelTemp.indices);
只需創建列表的副本:
model.indices = new List<int>(modelTemp.indices);
根據此S / O問題 ,最簡單的方法是在列表中調用ToList:
model.indices = modelTemp.indices.ToList();
您還可以將實例化為新列表,將列表作為構造函數參數傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.