Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从列表中保留值<;T>;在模型中清除列表后?_C#_Asp.net Mvc_Asp.net Mvc 4 - Fatal编程技术网

C# 如何从列表中保留值<;T>;在模型中清除列表后?

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

我有一个接收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
    }
}
列表索引=新列表();
foreach(docsRelacionadosModel中的var m)
{
//…做事
模型温度指数=指数;
//…在这里,我做了更多的工作,有时它会进入下一个迭代,我需要将值保留在索引中以获得更多的值。
//虽然情况不佳
if(isOk){
//我将此列表的值保存到模型
模型指数=模型温度指数;
//我需要清除列表以获得新值

index.Clear();您需要复制列表,并将该副本保存到
model.indices
。虽然复制列表的方法有很多种,但LINQ
ToList
扩展方法可能是最方便的:

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();
您还可以实例化为新列表,将列表作为构造函数参数传递