ToHashSet.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. ToHashSetAsync(source, comparer: null, cancellationToken);
  13. public static Task<HashSet<TSource>> ToHashSetAsync<TSource>(this IAsyncEnumerable<TSource> source, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken = default)
  14. {
  15. if (source == null)
  16. throw Error.ArgumentNull(nameof(source));
  17. return Core(source, comparer, cancellationToken);
  18. static async Task<HashSet<TSource>> Core(IAsyncEnumerable<TSource> _source, IEqualityComparer<TSource> _comparer, CancellationToken _cancellationToken)
  19. {
  20. var set = new HashSet<TSource>(_comparer);
  21. #if USE_AWAIT_FOREACH
  22. await foreach (TSource item in _source.WithCancellation(_cancellationToken).ConfigureAwait(false))
  23. {
  24. set.Add(item);
  25. }
  26. #else
  27. var e = _source.GetAsyncEnumerator(_cancellationToken);
  28. try
  29. {
  30. while (await e.MoveNextAsync().ConfigureAwait(false))
  31. {
  32. set.Add(e.Current);
  33. }
  34. }
  35. finally
  36. {
  37. await e.DisposeAsync().ConfigureAwait(false);
  38. }
  39. #endif
  40. return set;
  41. }
  42. }
  43. }
  44. }