有没有一种更加优雅的方式使用foreach循环编写这段代码?由于需要在pendingEntries不包含任何项时执行“创建新条目”的逻辑,所以这让我感到困扰。
ItemDto itemToAdd; // an input parameter to the method
IEnumerator<Item> pendingEntries = existingPendingItems.GetEnumerator();
pendingEntries.MoveNext();
do // foreach entry
{
Item entry = pendingEntries.Current;
if (entry != null) // fold the itemToAdd into the existing entry
{
entry.Quantity += itemToAdd.Quantity; // amongst other things
}
else // create a new entry
{
entry = Mapper.Map<ItemDto, Item>(itemToAdd);
}
Save(entry);
} while (pendingEntries.MoveNext());
Save(entry)
是什么意思?它是添加到existingPendingItems
还是其他列表中?如果在迭代过程中可以更改existingPendingItems
,则不应使用 foreach。 - Sjoerdwhile()
循环呢?当它无效时,你不应该访问Current - 请参阅下面的答案。 - Sjoerd