Difference between list.First(), list.ElementAt(0) and list[0]?

  1. .First() will throw an exception if the source list contains no elements. See the Remarks section. To avoid this, use FirstOrDefault().

  2. .ElementAt(0) will throw an exception if the index is greater than or equal to the number of elements in the list. To avoid this, use ElementAtOrDefault(0). If you're using LINQ To SQL, this can't be translated to sql, whereas .First() can translate to TOP 1.

  3. The indexer will also throw an exception if the index is greater than or equal to the number of elements in the list. It does not offer an OrDefault option to avoid this, and it cannot be translated to sql for LINQ To SQL. EDIT: I forgot to mention the simple obvious that if your object is an IEnumerable, you cannot use an indexer like this. If your object is an actual List, then you're fine.


Maybe an old question, but there is a performance difference.

for the code below:

 var lst = new List<int>();

            for (int i = 0; i < 1500; i++)
            {
                lst.Add(i);
            }
            int temp;


            Stopwatch sw1 = new Stopwatch();

            sw1.Start();

            for (int i = 0; i < 100; i++)
            {
                temp = lst[0];    
            }


            sw1.Stop();




            Stopwatch sw2 = new Stopwatch();
            sw2.Start();
            for (int i = 0; i < 100; i++)
            {
                temp = lst.First();
            }

            sw2.Stop();

            Stopwatch sw3 = new Stopwatch();
            sw3.Start();
            for (int i = 0; i < 100; i++)
            {
                temp = lst.ElementAt(0);
            }

            sw3.Stop();

you'll get the following times (in ticks):

  • lst[0]

    sw1.ElapsedTicks

    253

  • lst.First()

    sw2.ElapsedTicks

    438

  • lst.ElementAt(0)

    sw3.ElapsedTicks

    915


In the "valid" case (i.e., when a list has at least one element), they're the same as pointed out by APShredder. If there are no elements, then list[0] and list.ElementAt(0 will throw an ArgumentIndexOutOfRangeException, while list.First() will throw an InvalidOperationException.

Tags:

C#

List