Concerned about the optimality of working with LINQ. An acquaintance assured me that when I call. .ElementAt(N) , something like this happens behind the scenes:

 public static T ElementAt<T>(this IEnumerable<T> Data, int Index) { if (Index < 0) throw new ArgumentOutOfRangeException(); int i = 0; foreach(T x in Data) if (i++ == Index) return x; throw new ArgumentOutOfRangeException(); } 

As we understand, this is much slower than just getting an element by index in the same array, list, and so on. If this is true, and

 a[999]; // int[] a = new int[1000]; 

will work in ~ 1000 times faster than

 a.ElementAt(999); 

Is it possible to create an extension method for all classes that are guaranteed to have an indexer?

    1 answer 1

    This is not quite true . Almost all LINQ methods first do a check on the list. But if you already know that there is a list, then use parentheses, not LINQ. They are even shorter.

     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--; } } }