TakeLast.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. namespace System.Linq
  6. {
  7. public static partial class EnumerableEx
  8. {
  9. /// <summary>
  10. /// Returns a specified number of contiguous elements from the end of the sequence.
  11. /// </summary>
  12. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  13. /// <param name="source">Source sequence.</param>
  14. /// <param name="count">The number of elements to take from the end of the sequence.</param>
  15. /// <returns>Sequence with the specified number of elements counting from the end of the source sequence.</returns>
  16. public static IEnumerable<TSource> TakeLast<TSource>(this IEnumerable<TSource> source, int count)
  17. {
  18. if (source == null)
  19. throw new ArgumentNullException(nameof(source));
  20. if (count < 0)
  21. throw new ArgumentOutOfRangeException(nameof(count));
  22. return TakeLastCore(source, count);
  23. }
  24. private static IEnumerable<TSource> TakeLastCore<TSource>(IEnumerable<TSource> source, int count)
  25. {
  26. if (count == 0)
  27. {
  28. yield break;
  29. }
  30. var q = new Queue<TSource>(count);
  31. foreach (var item in source)
  32. {
  33. if (q.Count >= count)
  34. {
  35. q.Dequeue();
  36. }
  37. q.Enqueue(item);
  38. }
  39. while (q.Count > 0)
  40. {
  41. yield return q.Dequeue();
  42. }
  43. }
  44. }
  45. }