in

code for eternity !!!

community website for .net freaks ;-)

Technology

LINQ ElementAt and ElementAtOrDefault

We can use the ElementAt extension method of LINQ to return the element at a specified index (zero based) in a sequence. However the ElementAt extension method would throw the System.ArguementOutOfRangeException when the specified index is a negative value or not less than the size of the sequence. In such a scenario, we can use the ElementAtOrDefault extenion method which would return the default value of a type instead of throwing the System.ArguementOutOfRangeException.

Code example (both in C# and VB.NET) with comments below:

C#:

    // Create a new generic list of ints
    List<int> l = new List<int>();

    l.Add(1); // Add 1 to the list
    l.Add(5); // Add 5 to the list
    l.Add(3); // Add 3 to the list

    // Returns 1 as 1 exists at index 0
    int value = l.ElementAt(0);

    // Returns 3 as 3 exists at index 2
    value = l.ElementAt(2);

    // Returns the default value of int which is 0
    // since no element in the list exists at index 3
    value = l.ElementAtOrDefault(3);

    // Throws System.ArguementOutOfRangeException
    // since no element in the list exists at index 3
    value = l.ElementAt(3);

VB.NET:

    ' Create a new generic list of ints
    Dim l As New List(Of Integer)

    l.Add(1) ' Add 1 to the list
    l.Add(5) ' Add 5 to the list
    l.Add(3) ' Add 3 to the list

    ' Returns 1 as 1 exists at index 0
    Dim value As Integer = l.ElementAt(0)

    ' Returns 3 as 3 exists at index 2
    value = l.ElementAt(2)

    ' Returns the default value of int which is 0
    ' since no element in the list exists at index 3
    value = l.ElementAtOrDefault(3)

    ' Throws System.ArguementOutOfRangeException
    ' since no element in the list exists at index 3
    value = l.ElementAt(3)

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

Published Aug 13 2008, 03:02 PM by raj
Filed under: ,

I would really appreciate votes / kicks for this blog post if you found it useful ;-)

  kick it on DotNetKicks.com     Receive Email Updates


Comments

 

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

August 13, 2008 8:18 AM

Leave a Comment

(required)  
(optional)
(required)  
Add
Powered by Community Server (Non-Commercial Edition), by Telligent Systems