Utilities.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. internal static class Utilities
  10. {
  11. public static async ValueTask AddRangeAsync<T>(this List<T> list, IAsyncEnumerable<T> collection, CancellationToken cancellationToken)
  12. {
  13. if (collection is IEnumerable<T> enumerable)
  14. {
  15. list.AddRange(enumerable);
  16. return;
  17. }
  18. if (collection is IAsyncIListProvider<T> listProvider)
  19. {
  20. var count = await listProvider.GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
  21. if (count == 0)
  22. {
  23. return;
  24. }
  25. if (count > 0)
  26. {
  27. var newCount = list.Count + count;
  28. if (list.Capacity < newCount)
  29. {
  30. list.Capacity = newCount;
  31. }
  32. }
  33. }
  34. await foreach (var item in collection.WithCancellation(cancellationToken).ConfigureAwait(false))
  35. {
  36. list.Add(item);
  37. }
  38. }
  39. }
  40. }