[英]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.我正在寻求帮助,找到有人编写的 TakeLast 的扩展方法,该方法适用于 .Net Framework 的旧版本,如 4.6 及更高版本。 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默认的 TakeLast 方法仅适用于我的 .Net 5 和 .Net 6 项目,但我试图让我的程序在.Net Framework 上运行,我唯一不知道的是如何解决缺乏 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.