ToHashSet.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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>> ToHashSet<TSource>(this IAsyncEnumerable<TSource> source)
  12. {
  13. if (source == null)
  14. throw Error.ArgumentNull(nameof(source));
  15. return ToHashSetCore(source, EqualityComparer<TSource>.Default, CancellationToken.None);
  16. }
  17. public static Task<HashSet<TSource>> ToHashSet<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  18. {
  19. if (source == null)
  20. throw Error.ArgumentNull(nameof(source));
  21. return ToHashSetCore(source, EqualityComparer<TSource>.Default, cancellationToken);
  22. }
  23. public static Task<HashSet<TSource>> ToHashSet<TSource>(this IAsyncEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
  24. {
  25. if (source == null)
  26. throw Error.ArgumentNull(nameof(source));
  27. if (comparer == null)
  28. throw Error.ArgumentNull(nameof(comparer));
  29. return ToHashSetCore(source, comparer, CancellationToken.None);
  30. }
  31. public static Task<HashSet<TSource>> ToHashSet<TSource>(this IAsyncEnumerable<TSource> source, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken)
  32. {
  33. if (source == null)
  34. throw Error.ArgumentNull(nameof(source));
  35. if (comparer == null)
  36. throw Error.ArgumentNull(nameof(comparer));
  37. return ToHashSetCore(source, comparer, cancellationToken);
  38. }
  39. private static async Task<HashSet<TSource>> ToHashSetCore<TSource>(IAsyncEnumerable<TSource> source, IEqualityComparer<TSource> comparer, CancellationToken cancellationToken)
  40. {
  41. var e = source.GetAsyncEnumerator(cancellationToken);
  42. try
  43. {
  44. var set = new HashSet<TSource>(comparer);
  45. while (await e.MoveNextAsync().ConfigureAwait(false))
  46. {
  47. set.Add(e.Current);
  48. }
  49. return set;
  50. }
  51. finally
  52. {
  53. await e.DisposeAsync().ConfigureAwait(false);
  54. }
  55. }
  56. }
  57. }