ToHashSet.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  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 ValueTask<HashSet<TSource>> ToHashSetAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default) =>
  12. ToHashSetAsync(source, comparer: null, cancellationToken);
  13. public static ValueTask<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 ValueTask<HashSet<TSource>> Core(IAsyncEnumerable<TSource> source, IEqualityComparer<TSource>? comparer, CancellationToken cancellationToken)
  19. {
  20. var set = new HashSet<TSource>(comparer);
  21. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  22. {
  23. set.Add(item);
  24. }
  25. return set;
  26. }
  27. }
  28. }
  29. }