Take.cs 1.7 KB

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