SkipLast.cs 1.8 KB

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