不要在linq C#中取得最新记录

Kyl*_*Ren 4 c# linq

我们都知道,它Skip()可以忽略收集开始时不需要的记录。

但是Skip()在收集结束时是否有记录的方法?

您如何不获取集合中的最后一条记录?

还是您必须通过 Take()

即下面的代码,

var collection = MyCollection

var listCount = collection.Count();

var takeList = collection.Take(listCount - 1);
Run Code Online (Sandbox Code Playgroud)

这是排除集合中最后一条记录的唯一方法吗?

Fab*_*bio 5

使用枚举器,您可以通过一个枚举有效地延迟收益。

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)

  • @ HenrikHansen,OP的问题是关于跳过最后一条记录:_“如何不收集集合中的最后一条记录?” _。我想知道为什么每个人都试图实现多个项目的跳过。亚尼?;) (2认同)