SkipLast.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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 !(REFERENCE_ASSEMBLY && (NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER))
  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. throw new ArgumentNullException(nameof(source));
  24. if (count < 0)
  25. throw new ArgumentOutOfRangeException(nameof(count));
  26. return SkipLastCore(source, count);
  27. }
  28. private static IEnumerable<TSource> SkipLastCore<TSource>(this IEnumerable<TSource> source, int count)
  29. {
  30. var q = new Queue<TSource>();
  31. foreach (var x in source)
  32. {
  33. q.Enqueue(x);
  34. if (q.Count > count)
  35. {
  36. yield return q.Dequeue();
  37. }
  38. }
  39. }
  40. #endif
  41. }
  42. }