Skip to content

Commit

Permalink
Merge pull request #212 from svroonland/maybe-to-list
Browse files Browse the repository at this point in the history
Add Maybe<T>.ToList()
  • Loading branch information
vkhorikov authored Jul 10, 2020
2 parents c10e048 + 6d01cb0 commit 0c2a1ac
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
22 changes: 22 additions & 0 deletions CSharpFunctionalExtensions.Tests/MaybeTests/ExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,28 @@ public void TryFind_dict_does_not_contains_key()
maybe.HasValue.Should().BeFalse();
}

[Fact]
public void ToList_gives_empty_list_if_null()
{
Maybe<MyClass> maybe = null;

List<MyClass> myClasses = maybe.ToList();

myClasses.Count.Should().Be(0);
}

[Fact]
public void ToList_gives_single_item_list_if_not_null()
{
var instance = new MyClass();
Maybe<MyClass> maybe = instance;

List<MyClass> myClasses = maybe.ToList();

myClasses.Count.Should().Be(1);
myClasses[0].Should().Be(instance);
}

private static Maybe<string> GetPropertyIfExists(MyClass myClass)
{
return myClass.Property;
Expand Down
5 changes: 5 additions & 0 deletions CSharpFunctionalExtensions/Maybe/MaybeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ public static Result<T, E> ToResult<T, E>(this Maybe<T> maybe, E error)
return defaultValue;
}

public static List<T> ToList<T>(this Maybe<T> maybe)
{
return maybe.Unwrap(value => new List<T> {value}, new List<T>());
}

public static Maybe<T> Where<T>(this Maybe<T> maybe, Func<T, bool> predicate)
{
if (maybe.HasNoValue)
Expand Down

0 comments on commit 0c2a1ac

Please sign in to comment.