From 5981dd081dc5a56ae05543e6d19e295ac1321893 Mon Sep 17 00:00:00 2001 From: Kyle Ratti Date: Fri, 23 Sep 2022 21:08:48 -0400 Subject: [PATCH] fix: correct implementation of FirstOrEmpty --- Base/Structures/MaybeExtensions.cs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/Base/Structures/MaybeExtensions.cs b/Base/Structures/MaybeExtensions.cs index 55d08cc..733c574 100644 --- a/Base/Structures/MaybeExtensions.cs +++ b/Base/Structures/MaybeExtensions.cs @@ -2,8 +2,21 @@ public static class MaybeExtensions { - public static Maybe FirstOrEmpty(this IEnumerable col) => - col.FirstOrDefault() ?? Maybe.Empty(); + public static Maybe FirstOrEmpty(this IEnumerable collection) + { + using var enumerator = collection.GetEnumerator(); + + return !enumerator.MoveNext() ? Maybe.Empty() : enumerator.Current; + } + + public static Maybe FirstOrEmpty(this IEnumerable collection, Func pred) + { + foreach (var item in collection) + if (pred(item)) + return item; + + return Maybe.Empty(); + } public static T? ToNullable(this Maybe item) where T : struct => item.HasValue ? item.Value : null;