简体   繁体   中英

C# TakeLast Extension for .Net Framework 4.6 and newer versions

I'm looking for help finding an extension method for TakeLast that someone has written that can work for older versions of.Net Framework like 4.6 and higher. The default TakeLast method only works with my project for.Net 5 and.Net 6 but I'm trying to allow my program to be run on.Net Framework and the only thing I haven't been able to figure out is how to workaround the lack of TakeLast

You can implement your own extension method, something like this:

public static partial class EnumearbleExtensions {
  public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> source, int count) {
    if (null == source)
      throw new ArgumentNullException(nameof(source));
    if (count < 0)
      throw new ArgumentOutOfRangeException(nameof(count));

    if (0 == count)
      yield break;

    Queue<T> result = new Queue<T>();

    foreach (T item in source) {
      if (result.Count == count)
        result.Dequeue();

      result.Enqueue(item);
    }

    return result;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM