为Option扩展Linq

This commit is contained in:
Sanchime 2022-05-03 11:13:45 +08:00
parent 040f6d9759
commit 115d6766a5
1 changed files with 16 additions and 0 deletions

View File

@ -77,6 +77,22 @@ public static class OptionExtension
public static Option<T> OrElse<T>(this Option<T> left, Func<Option<T>> right)
=> left.Match(() => right(), (_) => left);
#region Linq式
public static Option<R> Select<T, R>(this Option<T> source, Func<T, R> mapping)
=> source.Map(mapping);
public static Option<T> Where<T, R>(this Option<T> source, Func<T, bool> predicate)
=> source.Match(() => Option.None, (val) => predicate(val) ? source : Option.None);
public static Option<RR> SelectMany<T, R, RR>(this Option<T> source, Func<T, Option<R>> binding, Func<T, R, RR> project)
=> source.Match(
None: () => Option.None,
Some: (val) => binding(val).Match(
None: () => Option.None,
Some: (res) => Option.Some(project(val, res))));
#endregion
}