Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • LINQ - Get Started
  • What is LINQ
  • Why LINQ
  • LINQ API
  • LINQ Query Syntax
  • LINQ Method Syntax
  • Lambda Expression
  • Standard Query Operators
  • Where
  • OfType
  • OrderBy
  • ThenBy
  • GroupBy, ToLookup
  • Join
  • GroupJoin
  • Select
  • All, Any
  • Contains
  • Aggregate
  • Average
  • Count
  • Max
  • Sum
  • ElementAt, ElementAtOrDefault
  • First, FirstOrDefault
  • Last, LastOrDefault
  • Single, SingleOrDefault
  • SequenceEqual
  • Concat
  • DefaultIfEmpty
  • Empty, Range, Repeat
  • Distinct
  • Except
  • Intersect
  • Union
  • Skip, SkipWhile
  • Take, TakeWhile
  • Conversion Operators
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Element Operators: ElementAt, ElementAtOrDefault

Element operators return a particular element from a sequence (collection).

The following table lists all the Element operators in LINQ.

Element Operators (Methods)Description
ElementAtReturns the element at a specified index in a collection
ElementAtOrDefaultReturns the element at a specified index in a collection or a default value if the index is out of range.
FirstReturns the first element of a collection, or the first element that satisfies a condition.
FirstOrDefaultReturns the first element of a collection, or the first element that satisfies a condition. Returns a default value if index is out of range.
LastReturns the last element of a collection, or the last element that satisfies a condition
LastOrDefaultReturns the last element of a collection, or the last element that satisfies a condition. Returns a default value if no such element exists.
SingleReturns the only element of a collection, or the only element that satisfies a condition.
SingleOrDefaultReturns 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.

The ElementAt() method returns an element from the specified index from a given collection. If the specified index is out of the range of a collection then it will throw an Index out of range exception. Please note that index is a zero based index.

The ElementAtOrDefault() method also returns an element from the specified index from a collaction and if the specified index is out of range of a collection then it will return a default value of the data type instead of throwing an error.

The following example demonstrates ElementAt and ElementAtOrDefault method on primitive collection.

Example: LINQ ElementAt() and ElementAtOrDefault() - C#
IList<int> intList = new List<int>() { 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { "One", "Two", null, "Four", "Five" };

Console.WriteLine("1st Element in intList: {0}", intList.ElementAt(0));
Console.WriteLine("1st Element in strList: {0}", strList.ElementAt(0));
		
Console.WriteLine("2nd Element in intList: {0}", intList.ElementAt(1));
Console.WriteLine("2nd Element in strList: {0}", strList.ElementAt(1));
		
Console.WriteLine("3rd Element in intList: {0}", intList.ElementAtOrDefault(2));
Console.WriteLine("3rd Element in strList: {0}", strList.ElementAtOrDefault(2));

Console.WriteLine("10th Element in intList: {0} - default int value", 
                intList.ElementAtOrDefault(9));		
Console.WriteLine("10th Element in strList: {0} - default string value (null)",
                 strList.ElementAtOrDefault(9));		
		
		
Console.WriteLine("intList.ElementAt(9) throws an exception: Index out of range");
Console.WriteLine("-------------------------------------------------------------");
Console.WriteLine(intList.ElementAt(9));
Try it
Output:
1st Element in intList: 10
1st Element in strList: One
2nd Element in intList: 21
2nd Element in strList: Two
3rd Element in intList: 30
3rd Element in strList:
10th Element in intList: 0 - default int value
10th Element in strList: - default string value (null)
intList.ElementAt(9) throws an exception: Index out of range
-------------------------------------------------------------
Run-time exception: Index was out of range....

As you can see in the above example, intList.ElementAtOrDefault(9) returns 0 (default value of int) because intList does not include 10th element. However intList.ElementAt(9) throws "Index out of range" exception.The same way, strList.ElementAtOrDefault(9) returns null which is default value of string type. (console display empty space because it cannot display null)

Thus, it is advisable to use the ElementAtOrDefault extension method to eliminate the possibility of a runtime exception.

Learn about another element operator First and FirstOrDefault in the next section.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.