加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 我可以将这个do-while循环重写为foreach循环吗?

发布时间:2020-12-16 01:46:16 所属栏目:百科 来源:网络整理
导读:有没有办法用foreach循环更优雅地编写这段代码? “创建新条目”逻辑阻碍了我,因为即使pendingEntries不包含任何项目,它也需要执行. ItemDto itemToAdd; // an input parameter to the methodIEnumeratorItem pendingEntries = existingPendingItems.GetEnum
有没有办法用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());

解决方法

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读