Skip to content

Commit 7a0f4fe

Browse files
committed
Use async iterators for OfType.
1 parent 490e2dd commit 7a0f4fe

File tree

1 file changed

+26
-0
lines changed
  • Ix.NET/Source/System.Linq.Async/System/Linq/Operators

1 file changed

+26
-0
lines changed

Ix.NET/Source/System.Linq.Async/System/Linq/Operators/OfType.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,45 @@
33
// See the LICENSE file in the project root for more information.
44

55
using System.Collections.Generic;
6+
using System.Threading;
67
using System.Threading.Tasks;
78

89
namespace System.Linq
910
{
1011
public static partial class AsyncEnumerable
1112
{
13+
// REVIEW: This is a non-standard LINQ operator, because we don't have a non-generic IAsyncEnumerable.
14+
//
15+
// Unfortunately, this has limited use because it requires the source to be IAsyncEnumerable<object>,
16+
// thus it doesn't bind for value types. Adding a first generic parameter for the element type of
17+
// the source is not an option, because it would require users to specify two type arguments, unlike
18+
// what's done in Enumerable.OfType. Should we move this method to Ix, thus doing away with OfType
19+
// in the API surface altogether?
20+
1221
public static IAsyncEnumerable<TResult> OfType<TResult>(this IAsyncEnumerable<object> source)
1322
{
1423
if (source == null)
1524
throw Error.ArgumentNull(nameof(source));
1625

26+
#if USE_ASYNC_ITERATOR
27+
return Create(Core);
28+
29+
async IAsyncEnumerator<TResult> Core(CancellationToken cancellationToken)
30+
{
31+
await foreach (var obj in AsyncEnumerableExtensions.WithCancellation(source, cancellationToken).ConfigureAwait(false))
32+
{
33+
if (obj is TResult result)
34+
{
35+
yield return result;
36+
}
37+
}
38+
}
39+
#else
1740
return new OfTypeAsyncIterator<TResult>(source);
41+
#endif
1842
}
1943

44+
#if !USE_ASYNC_ITERATOR
2045
private sealed class OfTypeAsyncIterator<TResult> : AsyncIterator<TResult>
2146
{
2247
private readonly IAsyncEnumerable<object> _source;
@@ -70,5 +95,6 @@ protected override async ValueTask<bool> MoveNextCore()
7095
return false;
7196
}
7297
}
98+
#endif
7399
}
74100
}

0 commit comments

Comments
 (0)