FruityFoundation/Base/Structures/MaybeExtensions.cs

34 lines
1.0 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
namespace FruityFoundation.Base.Structures;
2021-11-19 00:12:02 -05:00
public static class MaybeExtensions
{
public static Maybe<T> FirstOrEmpty<T>(this IEnumerable<T> collection)
{
using var enumerator = collection.GetEnumerator();
2023-08-01 22:12:54 -04:00
return !enumerator.MoveNext() ? Maybe.Empty<T>() : 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;
2023-08-01 22:12:54 -04:00
return Maybe.Empty<T>();
}
2021-11-19 00:12:02 -05:00
public static Maybe<TValue> TryGet<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key) =>
dict.TryGetValue(key, out var value) ? Maybe.Just(value) : Maybe.Empty<TValue>();
2023-08-01 22:12:54 -04:00
public static Maybe<TValue> TryGet<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dict, TKey key) =>
dict.TryGetValue(key, out var value) ? Maybe.Just(value) : Maybe.Empty<TValue>();
2021-11-19 00:12:02 -05:00
public static T? ToNullable<T>(this Maybe<T> item) where T : struct =>
item.HasValue ? item.Value : null;
2023-08-01 22:12:54 -04:00
}