我有一個包含 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
}
uj5u.com熱心網友回復:
既然你有一個串列,你可以按索引迭代:
// 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));
}
}
uj5u.com熱心網友回復:
由于您無法在迭代時修改串列,因此您可以在迭代之前制作一個副本:
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);
}
uj5u.com熱心網友回復:
我認為創建新串列和復制物件會更容易遵循方法。
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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360727.html
上一篇:如何在ASP.NETCoreMVC和.NET5中設定默認頁面?
下一篇:是否可以在包中包含外部檔案?
