Take.cs 1.8 KB

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