Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I use Enumerable.ElementAt() versus the [] operator?

Tags:

c#

This seems like a silly question, but I haven't found the answer, so here it is. :)

In both cases, you will get an "out-of-range" exception if you fail to check the bounds of your collection. Is this just coding style preference?

And in case someone needs an example:

List<byte> myList = new List<byte>(){0x01, 0x02, 0x03}; byte testByte = myList.ElementAt(2); 

versus

byte testByte = myList[2]; 
like image 706
EJA Avatar asked Mar 16 '11 14:03

EJA


People also ask

What is ElementAt C#?

ElementAt() is a System. Linq method in C# that is used to get and display element at a particular index. The following is our string array − string[] arr = { "One", "Two", "Three", "Four", "Five" }; Now to get an element at index 0, use the ElementAt() method − arr.ElementAt(0); The following is the complete code −

Which operator returns the element at a given index in sequence of default value if the index is out of range?

ElementAtOrDefault<TSource>(IEnumerable<TSource>, Index) Returns the element at a specified index in a sequence or a default value if the index is out of range.


2 Answers

Because Enumerable is more generic, and a collection represented by enumerable may not have an indexer.

But, if it does - don't use ElementAt() it's probably not going to be as efficient.

like image 76
Massif Avatar answered Sep 19 '22 18:09

Massif


ElementAt() provides a unified interface for all enumerations in C#. I tend to use it quite often as I like the common API.

If the underlying type supports random access (ie, it supports the [] operator), then ElementAt will make use of that. So the only overhead is an extra method call (which is almost never relevant).

If the underlying type does not support random access, then ElementAt() simulates it by iterating the enumeration until it arrives at the element you care about. This can be very expensive and even have side effects sometimes.

There is also ElementAtOrDefault() which is often very handy.

like image 25
Matt Greer Avatar answered Sep 21 '22 18:09

Matt Greer