Take.cs 1.8 KB

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