Can I "stop" a LINQ method chain midway?

I have the following method-chain in my code:

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

The issue with this code is that Handler.HandleForm() can return null in certain cases. If that is the case, I want to skip the rest of the methods for that form and just continue with the next item in the list.

Is there any way to do this without doing a null-check in every step?

Upvotes: 2

Views: 260

Answers (2)

user9799702
user9799702

Reputation:

Other approach would be to simplify your query by adding everything into .ForEach:

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

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

I suggest adding Where:

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

Upvotes: 9

Related Questions