You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LINQ方法链中途跳过返回null的元素?

Solution for Skipping Null Results in LINQ Method Chains

Absolutely! You can avoid repetitive null checks by filtering out null values early in your LINQ chain using the Where() operator. This ensures only non-null forms proceed to subsequent steps, keeping your code clean and declarative.

Here's how to adjust your existing code:

MyFormCollection
    .Select(form => Handler.HandleForm(form))
    .Where(form => form != null) // Filter out any nulls immediately after HandleForm
    .Select(form => { 
        form.Id = Guid.Empty; 
        form.OtherProperty = existingValue; 
        return form; 
    })
    .ToList()
    .ForEach(FormService.SaveForm);

Why this works:

  • The Where(form => form != null) clause acts as a gatekeeper: any null returned by Handler.HandleForm() gets discarded right away, so it never reaches the next Select() or the SaveForm call.
  • You don’t need to add null checks in the second Select() or worry about SaveForm receiving a null argument—all items moving forward are guaranteed to be non-null.

If you’re using C# 8.0 or later, you can also make your intent clearer with nullable reference types (by marking the return type of HandleForm as Form?), but the Where() filter is still the simplest way to enforce non-null flow in your LINQ chain.

内容的提问来源于stack exchange,提问作者Christian Wattengård

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:55:30