VA1267
VA1267

Reputation: 323

Adding an object to an existing list during iteration

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
}

Upvotes: 0

Views: 1370

Answers (3)

Fabio
Fabio

Reputation: 32443

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();

You can remove creation of extra arrays by introducing extension method

public static IEnumerable<Item> TryAddUpdatedClone(this Item item)
{
    yield return item;
    if (someCondition)
    {
        var updatedClone = // create clone with new values
        yield return updatedClone;
    }
}

// Usage
var newList = oldList.SelectMany(item => item.TryAddUpdatedClone()).ToList();

Upvotes: 1

ProgrammingLlama
ProgrammingLlama

Reputation: 38870

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));
    }
}

Upvotes: 3

RedX
RedX

Reputation: 15184

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);
}

Upvotes: 1

Related Questions