集合已经被修改,不能使用枚举。

public List<EncyTable> ListToJson (List<EncyTable> list)
{
List<EncyTable> listTemp = new List<EncyTable>();
int i;
listTemp = list.ToList<EncyTable>();//引用类型 转值类型
foreach (EncyTable item in list)
{
int up = item.UP_ENCY_ID;
listTemp.Remove(item);
i = 0;

foreach (EncyTable it in listTemp)
{
if (it == null)
continue;
if (it.ENCY_ID == up)
{
listTemp[i].EncyEntity = new List<EncyTable>();
listTemp[i].EncyEntity.Add(it);
break;
}
i++;
}
}
if (listTemp.Count == 0)
{
return listTemp;
}

return listTemp;
}

下面两句话是有区别的:

listTemp = list;

listTemp = list.ToList<EncyTable>();

第一句应用类型,遍历list 的时候如果修改了 listTemp 也就是修改了list,他们两个指向同一个地址。就像指针一样。

第二句则开辟了新的空间,并把list转成List<EncyTable>()(虽然本身就是这个类型的) 但是,下面修改listTemp 就不会报“ 集合已经修改,不能使用枚举操作。”

写一个随笔 记录下来。

原文地址:https://www.cnblogs.com/90nice/p/3103696.html