TakeLast.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 source.TakeLast_(count);
  23. }
  24. private static IEnumerable<TSource> TakeLast_<TSource>(this 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. q.Dequeue();
  35. q.Enqueue(item);
  36. }
  37. while (q.Count > 0)
  38. yield return q.Dequeue();
  39. }
  40. }
  41. }