public static TSource ElementAt <TSource>(this IEnumerable <TSource> source, int index) { IList <TSource> list = source as IList <TSource>; if (list != null) { return(list[index]); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } using (IEnumerator <TSource> iterator = source.GetEnumerator()) { Tuple <bool, TSource> result = iterator.ElementAt(index, -1); if (result.Item1) { return(result.Item2); } } throw new ArgumentOutOfRangeException(nameof(index)); }
private static Tuple <bool, TSource> ElementAt <TSource>( this IEnumerator <TSource> iterator, int targetIndex, int lastIndex) { if (iterator.MoveNext()) { int currentIndex = lastIndex + 1; return(currentIndex == targetIndex ? Tuple.Create(true, iterator.Current) : iterator.ElementAt(targetIndex, currentIndex)); } return(Tuple.Create(false, default(TSource))); }
public static TSource ElementAtOrDefault <TSource>(this IEnumerable <TSource> source, int index) { if (index >= 0) { IList <TSource> list = source as IList <TSource>; if (list != null) { if (index < list.Count) { return(list[index]); } } else { using (IEnumerator <TSource> iterator = source.GetEnumerator()) { return(iterator.ElementAt(index, -1).Item2); } } } return(default(TSource)); }