linq-ElementAt

源码:

       public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index) {
            if (source == null) throw Error.ArgumentNull("source");
            IList<TSource> list = source as IList<TSource>;
            if (list != null) return list[index];
            if (index < 0) throw Error.ArgumentOutOfRange("index");
            using (IEnumerator<TSource> e = source.GetEnumerator()) {
                while (true) {
                    if (!e.MoveNext()) throw Error.ArgumentOutOfRange("index");
                    if (index == 0) return e.Current;
                    index--;
                }
            }
        }
 
        public static TSource ElementAtOrDefault<TSource>(this IEnumerable<TSource> source, int index) {
            if (source == null) throw Error.ArgumentNull("source");
            if (index >= 0) {
                IList<TSource> list = source as IList<TSource>;
                if (list != null) {
                    if (index < list.Count) return list[index];
                }
                else {
                    using (IEnumerator<TSource> e = source.GetEnumerator()) {
                        while (true) {
                            if (!e.MoveNext()) break;
                            if (index == 0) return e.Current;
                            index--;
                        }
                    }
                }
            }
            return default(TSource);
        }

具体实现转换成了List<T>,使用下标获取值,还有使用了using。

posted @ 2021-11-16 15:50  vba是最好的语言  阅读(31)  评论(0编辑  收藏  举报