C# 如何从列表中保留值<;T>;在模型中清除列表后?
我有一个接收ID的列表。它在foreach语句外部实例化C# 如何从列表中保留值<;T>;在模型中清除列表后?,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我有一个接收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
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
}
}
列表索引=新列表();
foreach(docsRelacionadosModel中的var m)
{
//…做事
模型温度指数=指数;
//…在这里,我做了更多的工作,有时它会进入下一个迭代,我需要将值保留在索引中以获得更多的值。
//虽然情况不佳
if(isOk){
//我将此列表的值保存到模型
模型指数=模型温度指数;
//我需要清除列表以获得新值
index.Clear();您需要复制列表,并将该副本保存到model.indices
。虽然复制列表的方法有很多种,但LINQToList
扩展方法可能是最方便的:
model.indices = modelTemp.indices.ToList();
另一个选项是只使用列表
构造函数:
model.indices = new List<int>(modelTemp.indices);
model.index=新列表(modelTemp.index);
只需创建列表的副本:
model.indices = new List<int>(modelTemp.indices);
model.index=新列表(modelTemp.index);
根据,最简单的方法可能是调用列表中的ToList:
model.indices = modelTemp.indices.ToList();
您还可以实例化为新列表,将列表作为构造函数参数传递