Skip.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 !(REF_ASSM && NETCOREAPP2_0)
  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 source.SkipLast_(count);
  31. }
  32. #endif
  33. private static IEnumerable<TSource> SkipLast_<TSource>(this IEnumerable<TSource> source, int count)
  34. {
  35. var q = new Queue<TSource>();
  36. foreach (var x in source)
  37. {
  38. q.Enqueue(x);
  39. if (q.Count > count)
  40. {
  41. yield return q.Dequeue();
  42. }
  43. }
  44. }
  45. }
  46. }