123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- // Licensed to the .NET Foundation under one or more agreements.
- // The .NET Foundation licenses this file to you under the Apache 2.0 License.
- // See the LICENSE file in the project root for more information.
- using System.Collections.Generic;
- using System.Threading;
- using System.Threading.Tasks;
- namespace System.Linq
- {
- internal static class Utilities
- {
- public static async ValueTask AddRangeAsync<T>(this List<T> list, IAsyncEnumerable<T> collection, CancellationToken cancellationToken)
- {
- if (collection is IEnumerable<T> enumerable)
- {
- list.AddRange(enumerable);
- return;
- }
- if (collection is IAsyncIListProvider<T> listProvider)
- {
- var count = await listProvider.GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(false);
- if (count == 0)
- {
- return;
- }
- if (count > 0)
- {
- var newCount = list.Count + count;
- if (list.Capacity < newCount)
- {
- list.Capacity = newCount;
- }
- }
- }
- #if USE_AWAIT_FOREACH
- await foreach (var item in collection.WithCancellation(cancellationToken).ConfigureAwait(false))
- {
- list.Add(item);
- }
- #else
- var e = collection.GetAsyncEnumerator(cancellationToken);
- try
- {
- while (await e.MoveNextAsync().ConfigureAwait(false))
- {
- list.Add(e.Current);
- }
- }
- finally
- {
- await e.DisposeAsync().ConfigureAwait(false);
- }
- #endif
- }
- }
- }
|