我可以 "stop" 中途链接 LINQ 方法吗?
Can I "stop" a LINQ method chain midway?
我的代码中有以下方法链:
MyFormCollection
.Select(form => Handler.HandleForm(form))
.Select(form =>
{
form.Id = Guid.Empty;
form.OtherProperty = existingValue;
return form;
})
.ToList()
.ForEach(FormService.SaveForm);
此代码的问题是 Handler.HandleForm()
在某些情况下可能 return 为 null。如果是这样,我想跳过该表单的其余方法,只继续列表中的下一项。
有什么方法可以在不在每一步都进行空检查的情况下做到这一点?
我建议添加 Where
:
MyFormCollection
.Select(form => Handler.HandleForm(form))
.Where(form => form != null) // <- from this line on not null form(s) only
...
其他方法是通过将所有内容添加到 .ForEach 中来简化您的查询:
MyFormCollection.ToList()
.ForEach(form => {
if((form = Handler.HandleForm(form)) != null)
{
form.Id = Guid.Empty;
form.OtherProperty = existingValue;
FormService.SaveForm(f))
}
}
我的代码中有以下方法链:
MyFormCollection
.Select(form => Handler.HandleForm(form))
.Select(form =>
{
form.Id = Guid.Empty;
form.OtherProperty = existingValue;
return form;
})
.ToList()
.ForEach(FormService.SaveForm);
此代码的问题是 Handler.HandleForm()
在某些情况下可能 return 为 null。如果是这样,我想跳过该表单的其余方法,只继续列表中的下一项。
有什么方法可以在不在每一步都进行空检查的情况下做到这一点?
我建议添加 Where
:
MyFormCollection
.Select(form => Handler.HandleForm(form))
.Where(form => form != null) // <- from this line on not null form(s) only
...
其他方法是通过将所有内容添加到 .ForEach 中来简化您的查询:
MyFormCollection.ToList()
.ForEach(form => {
if((form = Handler.HandleForm(form)) != null)
{
form.Id = Guid.Empty;
form.OtherProperty = existingValue;
FormService.SaveForm(f))
}
}