fix: correct implementation of FirstOrEmpty

This commit is contained in:
Kyle Ratti 2022-09-23 21:08:48 -04:00
parent cdcfd671f0
commit 5981dd081d
No known key found for this signature in database
GPG Key ID: 321BA8EB09CD93F4

View File

@ -2,8 +2,21 @@
public static class MaybeExtensions
{
public static Maybe<T> FirstOrEmpty<T>(this IEnumerable<T> col) =>
col.FirstOrDefault() ?? Maybe<T>.Empty();
public static Maybe<T> FirstOrEmpty<T>(this IEnumerable<T> collection)
{
using var enumerator = collection.GetEnumerator();
return !enumerator.MoveNext() ? Maybe<T>.Empty() : enumerator.Current;
}
public static Maybe<T> FirstOrEmpty<T>(this IEnumerable<T> collection, Func<T, bool> pred)
{
foreach (var item in collection)
if (pred(item))
return item;
return Maybe<T>.Empty();
}
public static T? ToNullable<T>(this Maybe<T> item) where T : struct =>
item.HasValue ? item.Value : null;