大佬教程收集整理的这篇文章主要介绍了c# – 我可以将这个do-while循环重写为foreach循环吗?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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());
foreach (Item entry in existingPendingItems.DefaultIfEmpty()) { Item entryToSave; if (entry != null) // fold the itemToAdd into the existing entry { entry.Quantity += itemToAdd.Quantity; // amongst other things entryToSave = entry; } else // create a new entry { entryToSave = Mapper.Map<ItemDto,Item>(itemToAdd); } Save(entryToSave); }
关键是Enumerable.DefaultIfEmpty()调用 – 如果序列为空,这将返回带有默认(Item)项的序列.对于引用类型,这将为null.
编辑:修复了neotapir提到的bug.
以上是大佬教程为你收集整理的c# – 我可以将这个do-while循环重写为foreach循环吗?全部内容,希望文章能够帮你解决c# – 我可以将这个do-while循环重写为foreach循环吗?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。