diff --git a/CSharpFunctionalExtensions.Tests/ResultTests/Extensions/SelectTests.cs b/CSharpFunctionalExtensions.Tests/ResultTests/Extensions/SelectTests.cs new file mode 100644 index 00000000..ac96862b --- /dev/null +++ b/CSharpFunctionalExtensions.Tests/ResultTests/Extensions/SelectTests.cs @@ -0,0 +1,51 @@ +using FluentAssertions; +using Xunit; + +namespace CSharpFunctionalExtensions.Tests.ResultTests.Extensions; +public class SelectTests +{ + [Fact] + public void Select_returns_new_result() + { + Result result = new MyClass { Property = "Some value" }; + + Result result2 = result.Select(x => x.Property); + + result2.IsSuccess.Should().BeTrue(); + result2.GetValueOrDefault().Should().Be("Some value"); + } + + [Fact] + public void Select_returns_no_value_if_no_value_passed_in() + { + Result result = Result.Failure("error message"); + + Result result2 = result.Select(x => x); + + result2.IsSuccess.Should().BeFalse(); + result2.GetValueOrDefault().Should().Be(default); + } + + [Fact] + public void Result_Error_Select_from_class_to_struct_retains_Error() + { + Result.Failure("error message").Select(_ => 42).IsSuccess.Should().BeFalse(); + Result.Failure("error message").Select(_ => 42).Error.Should().Be("error message"); + } + + [Fact] + public void Result_can_be_used_with_linq_query_syntax() + { + Result name = "John"; + + Result upper = from x in name select x.ToUpper(); + + upper.IsSuccess.Should().BeTrue(); + upper.GetValueOrDefault().Should().Be("JOHN"); + } + + private class MyClass + { + public string Property { get; set; } + } +} diff --git a/CSharpFunctionalExtensions/Result/Methods/Extensions/Select.cs b/CSharpFunctionalExtensions/Result/Methods/Extensions/Select.cs new file mode 100644 index 00000000..a5b98853 --- /dev/null +++ b/CSharpFunctionalExtensions/Result/Methods/Extensions/Select.cs @@ -0,0 +1,15 @@ +using System; + +namespace CSharpFunctionalExtensions +{ + public static partial class ResultExtensions + { + /// + /// This method should be used in linq queries. We recommend using Map method. + /// + public static Result Select(in this Result result, Func selector) + { + return result.Map(selector); + } + } +}