You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Extension method IEnumerable<Result<TValue>>.Merge() enumerates passed results collection multiple times. This might cause side effects to be introduced multiple times; the following code sample throws an InvalidOperationException:
using FluentResults;varsth=new Something(
Enumerable.Range(1,5).ToHashSet());varresult= Enumerable.Range(6,2).Select(number => sth.AddNumber(number)).Merge();// Exception is thrown here;
Console.WriteLine($"Merger is a {(result.IsSuccess ?"success":"failure")}");internalclassSomething{privatereadonlyHashSet<int>numbers;publicSomething(HashSet<int>numbers){this.numbers =numbers;}publicResult<Something>AddNumber(intnumber)=>
Result.OkIf(numbers.Add(number),"Can't add a duplicate!").ToResult(this);}
The workaround is to materialize the results enumerable before merging. Fixing that requires change in the implementation of MergeWithValue to one that enumerates the collection once; the simplest (and the most dumbed-down) refactor would resemble this:
publicstaticResult<IEnumerable<TValue>>MergeWithValue<TValue>(IEnumerable<Result<TValue>>results){varvalues=newList<TValue>();varfinalResult= Result.Ok<IEnumerable<TValue>>(Array.Empty<TValue>());foreach(var result in results){
finalResult.Reasons.AddRange(result.Reasons);if(result.IsSuccess){
values.Add(result.Value);}}return finalResult.IsSuccess ? finalResult.WithValue(values):finalResult;}
Alternatively, results can be materialized first and then the rest can remain mostly unchanged:
Extension method
IEnumerable<Result<TValue>>.Merge()
enumerates passedresults
collection multiple times. This might cause side effects to be introduced multiple times; the following code sample throws anInvalidOperationException
:The workaround is to materialize the results enumerable before merging. Fixing that requires change in the implementation of
MergeWithValue
to one that enumerates the collection once; the simplest (and the most dumbed-down) refactor would resemble this:Alternatively,
results
can be materialized first and then the rest can remain mostly unchanged:The text was updated successfully, but these errors were encountered: