这在早期工作正常,但在我更新了这个开始破坏的newtonsoft版本之后还不确定。
这是我得到的错误:收集被修改;枚举操作可能无法执行。
JObject jObjectFull = (JObject)dynObjFullJArray[index];
JArray jArrayFull = (JArray)jObjectFull[packageName];
int fullCount = jObjectFull[packageName].Count();
if (packageName == "hello")
{
if (ishello)
{
ishellochck= false;
jArrayFull.RemoveAll();
}
jArrayFull.Add(JObject.FromObject(dynObjItem));
}
else
{
foreach (var item in jObjectFull[packageName])
{
int itemId = (int)item.SelectToken(selectedIdOrderNo.Split('|')[0]);
if (dynObjItemId == itemId)
{
//Edit
flag = true;
jArrayFull[i].Remove();
if (i == 0)
{
if (fullCount > 1)
jArrayFull[i].AddBeforeSelf(JObject.FromObject(dynObjItem));
else
jArrayFull.Add(JObject.FromObject(dynObjItem));
}
else
{
if (i == (fullCount - 1))
{
--i;
jArrayFull[i].AddAfterSelf(JObject.FromObject(dynObjItem));
}
else
jArrayFull[i].AddBeforeSelf(JObject.FromObject(dynObjItem));
}
}
i++;
}`
答案 0 :(得分:1)
您没有说明您使用的是什么版本的Json.NET,但是正确引发了异常,因为您正在修改通过其迭代的集合:< / p>
jObjectFull[packageName]
定义为jArrayFull[i].Remove()
,((JArray)jObjectFull[packageName]).RemoveAt(i)
时,您实际上正在执行IList<JToken>
,从而修改了集合。 JArray
实现了 JObject jObjectFull = (JObject)dynObjFullJArray[index];
JArray jArrayFull = (JArray)jObjectFull[packageName];
if (packageName == "hello")
{
if (ishello)
{
ishellochck = false;
jArrayFull.RemoveAll();
}
jArrayFull.Add(JObject.FromObject(dynObjItem));
}
else
{
for (int i = 0, fullCount = jArrayFull.Count; i < fullCount; i++)
{
int itemId = (int)jArrayFull[i].SelectToken(selectedIdOrderNo.Split('|')[0]);
if (dynObjItemId == itemId)
{
//Edit
flag = true;
jArrayFull[i] = JObject.FromObject(dynObjItem);
// Maybe break here?
}
}
}
,所以也许你只想做:
response