-1

I am trying to modify some values within the value of the List collection List<DataClass>. The value which I am trying to modify listValues[i].destinationValue and listValues[i].sourceKey which is also a list collection. When I am trying to add another value to the collection it works using foreach loop. But when it goes to next value in the foreach loop value it stops and I get the error: System.InvalidOperationException: 'Collection was modified;.

foreach (var listValue in listValues)
{
    if (listValue.hostName == data[4] && listValue.description == data[3] && listValue.ruleName == data[2])
    {
        var i = listValues.FindIndex(x => x.hostName.Equals(listValue.hostName));
        listValues[i].destinationValue.Add(data[0]);
        listValues[i].sourceKey.Add(data[1]);
    }
    else
    {
        listValues.Add(docValueModelClass);
    }
}

if (listValues.Count == 0)
{
    listValues.Add(docValueModelClass);
}

Can you please suggest, how can I overcome this?

Dhillli4u
  • 117
  • 12

1 Answers1

2

You can't edit same list or same enumerating list inside foreach loop, Because we using same list for enumerable.

just use for loop to edit - It works.

logeshpalani31
  • 1,416
  • 12
  • 33