Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added select overload with projection for result #567

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}
}