-
-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathAsyncExtensions.cs
More file actions
34 lines (28 loc) · 996 Bytes
/
AsyncExtensions.cs
File metadata and controls
34 lines (28 loc) · 996 Bytes
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
32
33
34
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Device.Net
{
internal static class AsyncExtensions
{
/// <summary>
/// TODO: Why do I need to do this? Why doesn't linq have this?
/// </summary>
public static async Task<T> FirstOrDefaultAsync<T>(this IEnumerable<T> enumerable, Func<T, Task<bool>> predicate = null, CancellationToken cancellationToken = default)
{
if (enumerable == null) throw new ArgumentNullException(nameof(enumerable));
if (predicate == null) return enumerable.FirstOrDefault();
foreach (var item in enumerable)
{
if (cancellationToken.IsCancellationRequested) return default;
if (await predicate(item).ConfigureAwait(false))
{
return item;
}
}
return default;
}
}
}