SkipLast.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. /// Bypasses a specified number of contiguous elements from the end of the sequence and returns the remaining elements.
  11. /// </summary>
  12. /// <typeparam name="TSource">Source sequence element type.</typeparam>
  13. /// <param name="source">Source sequence.</param>
  14. /// <param name="count">
  15. /// The number of elements to skip from the end of the sequence before returning the remaining
  16. /// elements.
  17. /// </param>
  18. /// <returns>Sequence bypassing the specified number of elements counting from the end of the source sequence.</returns>
  19. public static IEnumerable<TSource> SkipLast<TSource>(this IEnumerable<TSource> source, int count)
  20. {
  21. if (source == null)
  22. throw new ArgumentNullException(nameof(source));
  23. if (count < 0)
  24. throw new ArgumentOutOfRangeException(nameof(count));
  25. return source.SkipLast_(count);
  26. }
  27. private static IEnumerable<TSource> SkipLast_<TSource>(this IEnumerable<TSource> source, int count)
  28. {
  29. var q = new Queue<TSource>();
  30. foreach (var x in source)
  31. {
  32. q.Enqueue(x);
  33. if (q.Count > count)
  34. yield return q.Dequeue();
  35. }
  36. }
  37. }
  38. }