TakeLast.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. namespace System.Linq
  6. {
  7. public static partial class EnumerableEx
  8. {
  9. #if !(REFERENCE_ASSEMBLY && (NETCOREAPP2_1 || NETSTANDARD2_1 ))
  10. /// <summary>
  11. /// Returns a specified number of contiguous elements from the end of the sequence.
  12. /// </summary>
  13. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  14. /// <param name="source">Source sequence.</param>
  15. /// <param name="count">The number of elements to take from the end of the sequence.</param>
  16. /// <returns>Sequence with the specified number of elements counting from the end of the source sequence.</returns>
  17. public static IEnumerable<TSource> TakeLast<TSource>(this IEnumerable<TSource> source, int count)
  18. {
  19. if (source == null)
  20. throw new ArgumentNullException(nameof(source));
  21. if (count < 0)
  22. throw new ArgumentOutOfRangeException(nameof(count));
  23. return TakeLastCore(source, count);
  24. }
  25. #endif
  26. private static IEnumerable<TSource> TakeLastCore<TSource>(IEnumerable<TSource> source, int count)
  27. {
  28. if (count == 0)
  29. {
  30. yield break;
  31. }
  32. var q = new Queue<TSource>(count);
  33. foreach (var item in source)
  34. {
  35. if (q.Count >= count)
  36. {
  37. q.Dequeue();
  38. }
  39. q.Enqueue(item);
  40. }
  41. while (q.Count > 0)
  42. {
  43. yield return q.Dequeue();
  44. }
  45. }
  46. }
  47. }