【问题标题】:Can I "stop" a LINQ method chain midway?我可以中途“停止”一个 LINQ 方法链吗?
【发布时间】:2018-05-16 10:20:58
【问题描述】:

我的代码中有以下方法链:

MyFormCollection
    .Select(form => Handler.HandleForm(form))
    .Select(form =>
    {
        form.Id = Guid.Empty;
        form.OtherProperty = existingValue;
        return form;
    })
    .ToList()
    .ForEach(FormService.SaveForm);

此代码的问题是Handler.HandleForm() 在某些情况下可能返回 null。如果是这种情况,我想跳过该表单的其余方法,继续处理列表中的下一项。

有什么方法可以做到这一点,而无需在每一步都进行空检查?

【问题讨论】:

  • .Where(form => form != null)?为了过滤掉 nulls

标签: c# linq ienumerable


【解决方案1】:

建议加Where

MyFormCollection
    .Select(form => Handler.HandleForm(form))
    .Where(form => form != null) // <- from this line on not null form(s) only
    ...

【讨论】:

    【解决方案2】:

    其他方法是通过将所有内容添加到 .ForEach 中来简化您的查询:

    MyFormCollection.ToList()
        .ForEach(form => {
            if((form = Handler.HandleForm(form)) != null)
            {
               form.Id = Guid.Empty;
               form.OtherProperty = existingValue;
               FormService.SaveForm(f))
            }
         }
    

    【讨论】:

      猜你喜欢
      • 2018-02-14
      • 2013-01-14
      • 2014-12-29
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      相关资源
      最近更新 更多