如何在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 byHandler.HandleForm()gets discarded right away, so it never reaches the nextSelect()or theSaveFormcall. - You don’t need to add null checks in the second
Select()or worry aboutSaveFormreceiving 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
相关产品推荐
相关产品推荐

