我们都知道,它Skip()可以忽略收集开始时不需要的记录。
但是Skip()在收集结束时是否有记录的方法?
您如何不获取集合中的最后一条记录?
还是您必须通过 Take()
即下面的代码,
var collection = MyCollection
var listCount = collection.Count();
var takeList = collection.Take(listCount - 1);
Run Code Online (Sandbox Code Playgroud)
这是排除集合中最后一条记录的唯一方法吗?
使用枚举器,您可以通过一个枚举有效地延迟收益。
public static IEnumerable<T> WithoutLast<T>(this IEnumerable<T> source)
{
using (IEnumerator<T> e = source.GetEnumerator())
{
if (e.MoveNext() == false) yield break;
var current = e.Current;
while (e.MoveNext())
{
yield return current;
current = e.Current;
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法
var items = new int[] {};
items.WithoutLast(); // returns empty
var items = new int[] { 1 };
items.WithoutLast(); // returns empty
var items = new int[] { 1, 2 };
items.WithoutLast(); // returns { 1 }
var items = new int[] { 1, 2, 3 };
items.WithoutLast(); // returns { 1, 2 }
Run Code Online (Sandbox Code Playgroud)