c# - LastOrDefault() 和 Last() 方法是否迭代列表的每个元素?

标签 c# .net list enumeration

LastOrDefault() 和 Last() 方法是否迭代列表中的每个元素以找到最后一个元素?或者他们是否通过基于元素的 index 搜索返回值?

最佳答案

如果它是 IList 类型,则不会,它不会迭代每个元素,因为那样效率很低。

他们是这样做的:

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> e = source.GetEnumerator()) {
                if (e.MoveNext()) {
                    TSource result;
                    do {
                        result = e.Current;
                    } while (e.MoveNext());
                    return result;
                }
            }
        }
        throw Error.NoElements();
    }

LastOrDefault:

public static TSource LastOrDefault<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> e = source.GetEnumerator()) {
                    if (e.MoveNext()) {
                        TSource result;
                        do {
                            result = e.Current;
                        } while (e.MoveNext());
                        return result;
                    }
                }
            }
            return default(TSource);
}

请注意,由于每个方法都有几个重载,我在上面只显示了一个,但如果您对其他方法感兴趣,那么 feel free to have a look at the source code :

关于c# - LastOrDefault() 和 Last() 方法是否迭代列表的每个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51349080/

相关文章:

c# - 在c#中获取Powershell脚本的错误并用条件语句输出它?

c# - 单元测试自定义 OnRender-Method

c# - 两个表的 Fluent Nhibernate 映射一对多在映射中使用唯一而不是主键

asp.net - 如何在 Nuget 中排除/不显示 .NET Framework 包?

c# - 记录所有在 Windows 中关闭的 Windows

list - Scala:为什么 foldLeft 不能用于两个列表的连接?

c# - 访问证书时出错 : Keyset Does Not Exist

c# - MySqlDataReader.GetBytes

python - 在 python 中制作副本

python - 如何使用 Python 将 2 列写入/追加到 .txt 文件中?