加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – List.Last()是否枚举集合?

发布时间:2020-12-15 17:48:54 所属栏目:百科 来源:网络整理
导读:考虑到 List 的边界是已知的.Last()是否枚举集合? 我问这个是因为documentation说它是由Enumerable定义的(在这种情况下,它需要枚举集合) 如果它枚举了集合,那么我可以通过索引简单地访问最后一个元素(因为我们知道List的.Count),但是看起来很愚蠢的必须这样
考虑到 List的边界是已知的.Last()是否枚举集合?

我问这个是因为documentation说它是由Enumerable定义的(在这种情况下,它需要枚举集合)

如果它枚举了集合,那么我可以通过索引简单地访问最后一个元素(因为我们知道List的.Count),但是看起来很愚蠢的必须这样做….

解决方法

如果它是一个IEnumerable< T>而不是IList< T(具有阵列或列表将使用索引). Enumerable.Last以下列方式实现(ILSpy):
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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读