在迭代期间将对象添加到现有列表

Adding an object to an existing list during iteration

我有一个包含 5 个对象的列表。

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

我有一个要求,在遍历列表时,如果满足某些条件,我需要创建当前对象的副本并修改一个 属性 并将其添加回 listA。 我可以创建一个单独的列表,在 for 循环之后,我可以将它添加到 listA,但是有没有更好的方法来实现这一点?

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

由于您无法在迭代时修改列表,因此您可以在迭代之前制作一个副本:

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

既然你有一个列表,你可以按索引迭代:

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

我认为创建新列表和复制对象的方法更简单。

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

您可以通过引入扩展方法来移除额外数组的创建

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