c# - Enumerable.Last<T>() 和 C# 数组

标签 c# .net arrays linq ienumerable

假设我有一个简单的数组:

double[] myDoubleArray = new double[] { 0, 1, 2, 3, 4, 5 };

这是高效的吗:

double last = myDoubleArray.Last();

这样吗?

double last = myDoubleArray[myDoubleArray.Length - 1];

即使可以进行上述优化,Last() 是否会遍历整个数组?

如果我传递了其他一些 IEnumerable(比如已生成的一个),Last() 将枚举序列。我更喜欢使用 Last(),因为代码看起来更干净,但如果它枚举序列,我不会做出牺牲。

最佳答案

不,它不会遍历所有元素。这是来自反射器的 Enumerable.Last() 的代码。如你所见,它做了这样的优化

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

关于c# - Enumerable.Last<T>() 和 C# 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5595777/

相关文章:

javascript - 我正在尝试使用 jquery 创建一个包含列的 div,但我无法让我的数组正确格式化

c# - 异常处理 : Thread v/s Task

c# - .net 集合内存优化 - 这种方法有效吗?

C# 相当于使用 python 切片操作旋转列表

.net - NetTcpBinding 和 WsHttpBinding 由哪些组件(绑定(bind)元素)组成?

arrays - 如何在 scala 中比较两个数组?

c# - 根据后代节点的属性选择节点的最佳 LINQ-to-XML 查询?

c# - 遍历对象的属性并获取 DateTime 类型属性的值

c# - "System.IO.IOException: The process cannot access the file ' C :\Test\test. 文本 ' because it is being used by another process"

java - 如何一次检查多个变量?