Using LINQ ElementAt and LINQ ElementAtOrDefault

LINQ provides two extension methods for retreiving the element at a given index in a List or other IEnumerable object. ElementAt returns the element at a given index, but can throw a System.ArguementOutOfRangeException when the specified index is a
negative value or not less than the size of the sequence. ElementAtOrDefault returns the element at a given index, or the defaultvalue of the list type. For value types (ints and bools for example), the default value is the initial value of the type, which is usually 0. For reference types (objects), the default value is usually null, although this can be overriden.

LINQ ElementAt and LINQ ElementAtOrDefault Example:

// 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);

 

share save 171 16 Using LINQ ElementAt and LINQ ElementAtOrDefault

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Leave a Reply