linq Last()如何确定最后一项? [英] How does linq Last() determine the last item?

查看:45
本文介绍了linq Last()如何确定最后一项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白Current如何可以为null,而LINQ函数Last()可以返回一个对象.我以为Last使用GetEnumerator并一直进行到当前== null并返回对象.但是,如您所见,第一个GetEnumerator().Current为null,最后以某种方式返回对象.

I don't understand how Current can be null and the LINQ function Last() can return an object. I thought Last uses GetEnumerator and keeps going until current == null and returns the object. However as you can see the first GetEnumerator().Current is null and last somehow returns an object.

linq Last()如何工作?

How does linq Last() work?

items.GetEnumerator().Current
items.Last()

推荐答案

通过使用 Reflector System.Core.dll 上的a>:

From using Reflector on System.Core.dll:

public static TSource Last<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    IList<TSource> list = source as IList<TSource>;
    if (list != null)
    {
        int count = list.Count;
        if (count > 0)
        {
            return list[count - 1];
        }
    }
    else
    {
        using (IEnumerator<TSource> enumerator = source.GetEnumerator())
        {
            if (enumerator.MoveNext())
            {
                TSource current;
                do
                {
                    current = enumerator.Current;
                }
                while (enumerator.MoveNext());
                return current;
            }
        }
    }
    throw Error.NoElements();
}

这篇关于linq Last()如何确定最后一项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆