ToHashSet.cs 2.1 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>> ToHashSet<TSource>(this IAsyncEnumerable<TSource> source)
  12. {
  13. if (source == null)
  14. throw new ArgumentNullException(nameof(source));
  15. return ToHashSet(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 new ArgumentNullException(nameof(source));
  21. return ToHashSet(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 new ArgumentNullException(nameof(source));
  27. if (comparer == null)
  28. throw new ArgumentNullException(nameof(comparer));
  29. return ToHashSet(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 new ArgumentNullException(nameof(source));
  35. if (comparer == null)
  36. throw new ArgumentNullException(nameof(comparer));
  37. return source.Aggregate(
  38. new HashSet<TSource>(comparer),
  39. (set, x) =>
  40. {
  41. set.Add(x);
  42. return set;
  43. },
  44. cancellationToken
  45. );
  46. }
  47. }
  48. }