Skip to content

Commit

Permalink
Merge pull request #567 from christophercalm/result-select-linq-query…
Browse files Browse the repository at this point in the history
…-enable

added select overload with projection for result
  • Loading branch information
vkhorikov authored Nov 18, 2024
2 parents b421543 + 9a80bf2 commit 443a364
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using FluentAssertions;
using Xunit;

namespace CSharpFunctionalExtensions.Tests.ResultTests.Extensions;
public class SelectTests
{
[Fact]
public void Select_returns_new_result()
{
Result<MyClass> result = new MyClass { Property = "Some value" };

Result<string> 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<MyClass> result = Result.Failure<MyClass>("error message");

Result<MyClass> 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<string>("error message").Select(_ => 42).IsSuccess.Should().BeFalse();
Result.Failure<string>("error message").Select(_ => 42).Error.Should().Be("error message");
}

[Fact]
public void Result_can_be_used_with_linq_query_syntax()
{
Result<string> name = "John";

Result<string> 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; }
}
}
15 changes: 15 additions & 0 deletions CSharpFunctionalExtensions/Result/Methods/Extensions/Select.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;

namespace CSharpFunctionalExtensions
{
public static partial class ResultExtensions
{
/// <summary>
/// This method should be used in linq queries. We recommend using Map method.
/// </summary>
public static Result<K> Select<T, K>(in this Result<T> result, Func<T, K> selector)
{
return result.Map(selector);
}
}
}

0 comments on commit 443a364

Please sign in to comment.