ToHashSet.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerable
  10. {
  11. public static Task<HashSet<TSource>> ToHashSetAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
  12. {
  13. if (source == null)
  14. throw Error.ArgumentNull(nameof(source));
  15. return ToHashSetCore(source, comparer: null, cancellationToken);
  16. }
  17. public static Task<HashSet<TSource>> ToHashSetAsync<TSource>(this IAsyncEnumerable<TSource> source, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken = default)
  18. {
  19. if (source == null)
  20. throw Error.ArgumentNull(nameof(source));
  21. return ToHashSetCore(source, comparer, cancellationToken);
  22. }
  23. private static async Task<HashSet<TSource>> ToHashSetCore<TSource>(IAsyncEnumerable<TSource> source, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken)
  24. {
  25. var set = new HashSet<TSource>(comparer);
  26. #if CSHARP8 && AETOR_HAS_CT // CS0656 Missing compiler required member 'System.Collections.Generic.IAsyncEnumerable`1.GetAsyncEnumerator'
  27. await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  28. {
  29. set.Add(item);
  30. }
  31. #else
  32. var e = source.GetAsyncEnumerator(cancellationToken);
  33. try
  34. {
  35. while (await e.MoveNextAsync().ConfigureAwait(false))
  36. {
  37. set.Add(e.Current);
  38. }
  39. }
  40. finally
  41. {
  42. await e.DisposeAsync().ConfigureAwait(false);
  43. }
  44. #endif
  45. return set;
  46. }
  47. }
  48. }