Element operations return a single, specific element from a sequence.
ElementAt
Returns the element at a specified index in a collection.
Method Syntax
// ElementAt var strings = new string[] { "zero", "one", "two", "three" }; var str = strings.ElementAt(2); // str = "two"
Query Syntax
// Not Applicable.
ElementAtOrDefault
Returns the element at a specified index in a collection or a default value if the index is out of range.
Method Syntax
// ElementAtOrDefault var strings = new string[] { "zero", "one", "two", "three" }; var str = strings.ElementAtOrDefault(10); // str = null
Query Syntax
// Not Applicable.
First
Returns the first element of a collection, or the first element that satisfies a condition.
Method Syntax
// First var numbers = new int[] { 1, 2, 3, 4, 5 }; var first = strings.First(); // first = 1
Query Syntax
// Not Applicable.
FirstOrDefault
Returns the first element of a collection, or the first element that satisfies a condition. Returns a default value if no such element exists.
Method Syntax
// FirstOrDefault var numbers = new int[] { 1, 2, 3, 4, 5 }; var firstGreaterThanTen = strings.FirstOrDefault(n => n > 10); // firstGreaterThanTen = 0
Query Syntax
// Not Applicable.
Last
Returns the last element of a collection, or the last element that satisfies a condition.
Method Syntax
// Last var numbers = new int[] { 1, 2, 3, 4, 5 }; var last = strings.Last(); // last = 5
Query Syntax
// Not Applicable.
LastOrDefault
Returns the last element of a collection, or the last element that satisfies a condition. Returns a default value if no such element exists.
Method Syntax
// LastOrDefault var numbers = new int[] { 1, 2, 3, 4, 5 }; var lastGreaterThanTen = strings.LastOrDefault(n => n > 10); // lastGreaterThanTen = 0
Query Syntax
// Not Applicable.
Single
Returns the only element of a collection, or the only element that satisfies a condition.
Method Syntax
// Single var numbers = new int[] { 1 }; var single = strings.Single(); // single = 1
Query Syntax
// Not Applicable.
SingleOrDefault
Returns the only element of a collection, or the only element that satisfies a condition. Returns a default value if no such element exists or the collection does not contain exactly one element.
Method Syntax
// SingleOrDefault var numbers = new int[] { 1, 2, 3, 4, 5 }; var singleGreaterThanFour = strings.SingleOrDefault(n => n > 4); // singleGreaterThanFour = 5
Query Syntax
// Not Applicable.