ToHashSet.cs 2.3 KB

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