// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT License. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace System.Linq { public static partial class EnumerableEx { #if !(REFERENCE_ASSEMBLY && (NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER )) /// /// Returns a specified number of contiguous elements from the end of the sequence. /// /// Source sequence element type. /// Source sequence. /// The number of elements to take from the end of the sequence. /// Sequence with the specified number of elements counting from the end of the source sequence. public static IEnumerable TakeLast(this IEnumerable source, int count) { if (source == null) throw new ArgumentNullException(nameof(source)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); return TakeLastCore(source, count); } private static IEnumerable TakeLastCore(IEnumerable source, int count) { if (count == 0) { yield break; } var q = new Queue(count); foreach (var item in source) { if (q.Count >= count) { q.Dequeue(); } q.Enqueue(item); } while (q.Count > 0) { yield return q.Dequeue(); } } #endif } }