From 8cfbe6a9cbbeca0bdc69e7921b7decbdb3bc6ee8 Mon Sep 17 00:00:00 2001 From: Steven Vroonland Date: Thu, 9 Jul 2020 11:28:08 +0200 Subject: [PATCH 1/2] Add Maybe.ToList() --- CSharpFunctionalExtensions/Maybe/MaybeExtensions.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CSharpFunctionalExtensions/Maybe/MaybeExtensions.cs b/CSharpFunctionalExtensions/Maybe/MaybeExtensions.cs index 4b7d0cfe..266e453a 100644 --- a/CSharpFunctionalExtensions/Maybe/MaybeExtensions.cs +++ b/CSharpFunctionalExtensions/Maybe/MaybeExtensions.cs @@ -35,6 +35,11 @@ public static Result ToResult(this Maybe maybe, E error) return defaultValue; } + public static List ToList(this Maybe maybe) + { + return maybe.Unwrap(value => new List {value}, new List()); + } + public static Maybe Where(this Maybe maybe, Func predicate) { if (maybe.HasNoValue) From 6d01cb04b26455e6f88e482af93731b5eb3b9ff7 Mon Sep 17 00:00:00 2001 From: Steven Vroonland Date: Thu, 9 Jul 2020 21:35:12 +0200 Subject: [PATCH 2/2] Add unit tests --- .../MaybeTests/ExtensionsTests.cs | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/CSharpFunctionalExtensions.Tests/MaybeTests/ExtensionsTests.cs b/CSharpFunctionalExtensions.Tests/MaybeTests/ExtensionsTests.cs index cd074e22..fa460e8e 100644 --- a/CSharpFunctionalExtensions.Tests/MaybeTests/ExtensionsTests.cs +++ b/CSharpFunctionalExtensions.Tests/MaybeTests/ExtensionsTests.cs @@ -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 maybe = null; + + List myClasses = maybe.ToList(); + + myClasses.Count.Should().Be(0); + } + + [Fact] + public void ToList_gives_single_item_list_if_not_null() + { + var instance = new MyClass(); + Maybe maybe = instance; + + List myClasses = maybe.ToList(); + + myClasses.Count.Should().Be(1); + myClasses[0].Should().Be(instance); + } + private static Maybe GetPropertyIfExists(MyClass myClass) { return myClass.Property;