Skip.cs 1.7 KB

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