-
Notifications
You must be signed in to change notification settings - Fork 0
/
FirstOrNoneAsync.cs
31 lines (28 loc) · 1.47 KB
/
FirstOrNoneAsync.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System.Linq.Expressions;
using Funcky.Monads;
using Microsoft.EntityFrameworkCore;
namespace Funcky.Extensions;
public static partial class EntityFrameworkQueryableExtensions
{
/// <summary>
/// Returns the first element of a sequence as an <see cref="Option" />, or a <see cref="Option{T}.None" /> value if the sequence contains no elements.
/// </summary>
/// <typeparam name="TSource">the inner type of the queryable.</typeparam>
public static async Task<Option<TSource>> FirstOrNoneAsync<TSource>(this IQueryable<TSource> source, CancellationToken cancellationToken = default)
where TSource : notnull
=> await source
.Select(x => Option.Some(x))
.FirstOrDefaultAsync(cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// Returns the first element of the sequence as an <see cref="Option{T}" /> that satisfies a condition or a <see cref="Option{T}.None" /> value if no such element is found.
/// </summary>
/// <typeparam name="TSource">the inner type of the queryable.</typeparam>
public static async Task<Option<TSource>> FirstOrNoneAsync<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate, CancellationToken cancellationToken = default)
where TSource : notnull
=> await source
.Where(predicate)
.Select(x => Option.Some(x))
.FirstOrDefaultAsync(cancellationToken)
.ConfigureAwait(false);
}