是的IEnumerable< T>。去年()的名单,其中最优化; T>? [英] Is IEnumerable<T>.Last() optimized for List<T>?

查看:108
本文介绍了是的IEnumerable< T>。去年()的名单,其中最优化; T>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名单,其中,T> ,名为,含N项

I have a List<T>, called L, containing N items.

L.Last()的IEnumerable&LT; T&GT; 扩展方法,经历所有N运行在线性时间的项目?

Is L.Last(), the IEnumerable<T> extension method, going to run through all N items in linear-time?

抑或是内部优化有的稳定的性能L [L.Count - 1]

推荐答案

你是对的,如果你看一下在code如何落实最后(从反射镜):

You are right, if you take a look the code how to implement Last (from Reflector):

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();
}

它实际上是优化了名单,其中,T&GT; 通过返回列表[计数 - 1];

这篇关于是的IEnumerable&LT; T&GT;。去年()的名单,其中最优化; T&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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