Home > front end >  Adding an object to an existing list during iteration
Adding an object to an existing list during iteration

Time:11-18

I have a list which consists of 5 objects.

List<ObjA> listA = new List<ObjA>();

I have a requirement where while iterating through the list , if some condition is met I need to create a copy of the current object and modify one property and add it back to the listA. I can create a separate list and after the for loop, I can add it to listA but is there any better way to achieve this?

foreach(var a in listA)
{
  //if(a.somecondition is true)
  // create a clone of 'a' and add it to listA
}

CodePudding user response:

Since you have a list, you can iterate by index:

// save the length before we iterate so that we don't iterate into new items
int length = listA.Count; 

// loop from 0 to the original length
for (int i = 0; i < length;   i)
{
    var a = listA[i];
    if (a.somecondition)
    {
        listA.Add(YourCloneMethod(a));
    }
}

CodePudding user response:

Since you can't modify a list while it iterates you can make a copy before you iterate:

foreach(var a in listA.ToList())
{
  //if(a.somecondition is true)
  // create a clone of 'a' and add it to listA
  var copyOfA = /* make copy of a */.
  listA.Add(copyOfA);
}

CodePudding user response:

I think creating new list and copy object there would be simpler to follow approach.

var newList = oldList.SelectMany(item =>
{
    if (someCondition) 
    {
        var updatedClone = // create clone
        return new[] { item, updatedClone };
    }
    return new[] { item };      
}).ToList();
  • Related