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。
标签:index,return,list,linq,source,IList,ElementAt,null 来源: https://www.cnblogs.com/Insist-Y/p/15561571.html