What is the performance of the Last() extension method for List?

前端 未结 5 1351
慢半拍i
慢半拍i 2020-11-30 11:06

I really like Last() and would use it all the time for Lists. But since it seems to be defined for IEnumerable, I gu

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 11:13

    You can just use Last with List without worrying :)

    Enumerable.Last attempts to downcast the IEnumerable instance to IList . If this is possible, it uses the indexer and Count property.

    Here is part of the implementation as Reflector sees it:

    IList list = source as IList;
    if (list != null)
    {
        int count = list.Count;
        if (count > 0)
        {
            return list[count - 1];
        }
    }
    

提交回复
热议问题