CSharpFunctionalExtensions icon indicating copy to clipboard operation
CSharpFunctionalExtensions copied to clipboard

IEnumerable<Result<T>> to Result<IEnumerable<T>>

Open FrancoisM opened this issue 6 years ago • 2 comments

For anyone interested:

public static class ResultExtensions
    {
        public static bool IsFailure<T>(this IEnumerable<Result<T>> source) => source.Any(result => result.IsFailure);
        public static bool IsSuccess<T>(this IEnumerable<Result<T>> source) => !source.IsFailure();
        public static Result<IEnumerable<T>> ToResult<T>(this IEnumerable<Result<T>> source)
        {
            var sourceList = source.ToList();
            return sourceList.IsFailure()
                ? Result.Fail<IEnumerable<T>>(sourceList.Error())
                : Result.Ok(sourceList.Select(result => result.Value));
        }
        public static string Error<T>(this IEnumerable<Result<T>> source)
        {
            var sourceList = source.ToList();
            return sourceList.IsSuccess()
                ? default
                : sourceList
                    .Where(result => result.IsFailure)
                    .Select(result => result.Error)
                    .Aggregate(new StringBuilder(), (stringBuilder, error) => stringBuilder.AppendLine(error))
                    .ToString();
        }
    }

FrancoisM avatar Feb 21 '19 12:02 FrancoisM

Hi @FrancoisM I think It method already exists: public static Result<IEnumerable<T>> Combine<T>(this IEnumerable<Result<T>> results, string errorMessagesSeparator)

a-z-hub avatar May 13 '19 19:05 a-z-hub

@ahryshchanka

I am trying to use that method, but I don't see that method signature on the Result struct in the latest version, 2.2.2.0, on NuGet. Has that feature not been released yet?

image

Edit:

Just realized the Combine method I was looking for was an IEnumerable<Result<T>> extension method, not a Result extension method.

codyspeck avatar Dec 11 '19 17:12 codyspeck