TakeLast.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. #if !(NETCOREAPP2_0 || 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. {
  21. throw new ArgumentNullException(nameof(source));
  22. }
  23. if (count < 0)
  24. {
  25. throw new ArgumentOutOfRangeException(nameof(count));
  26. }
  27. return TakeLastCore(source, count);
  28. }
  29. private static IEnumerable<TSource> TakeLastCore<TSource>(IEnumerable<TSource> source, int count)
  30. {
  31. if (count == 0)
  32. {
  33. yield break;
  34. }
  35. var q = new Queue<TSource>(count);
  36. foreach (var item in source)
  37. {
  38. if (q.Count >= count)
  39. {
  40. q.Dequeue();
  41. }
  42. q.Enqueue(item);
  43. }
  44. while (q.Count > 0)
  45. {
  46. yield return q.Dequeue();
  47. }
  48. }
  49. #endif
  50. }
  51. }