How can I replace this foreach loop with something else to achieve a more 'functional programming' approach?

Viewed 155

I am trying to write functional code, and I would like to avoid using the foreach loop below. How can I accomplish that?

I am using LanguageExt.

var errors = ImmutableArray.Create<ValidationError>();
var context = new ValidationContext<TRequest>(request);
foreach (IValidator<TRequest> validator in Validators)
{
    var validationResult = await validator.ValidateAsync(context, cancellationToken);
    if (!validationResult.IsValid)
    {
        errors = errors.AddRange(
            validationResult.Errors.
                Select(x => new ValidationError(Key: x.PropertyName, Message: x.ErrorMessage)));
    }

    if (cancellationToken.IsCancellationRequested)
        break;
}
if (errors.Any())
    return new BadRequestResponse(errors);
return SuccessResponse();
0 Answers
Related