Element Operators in LINQ

by Sachin Singh

Posted on Saturday, 06 February 2021

Tags: Element Operators in LINQ

In order to understand Element Operators , first analyze following questions, based on the collection shown below and think about their solution.

 List<int> numbers= new List<int>(){2,3,4,7,1,10};

1. Find the First element in the collection
  2. Find the Last element in the collection
  3.Find the 3rd element in the collection.
  4.Find single element divisible by 3 , if more than one element is divisible by 3 then return default value.

Notice, in all the questions mentioned above , we are trying to find a specific element in the collection, like element at first postion, last position , a specific postion or a single element. For all these types of requirement we have different Element operators in LINQ like First() operator,Last() operator,ElementAt() operator and Single() operator.

Now , look at the collection shown below, notice, the collection is empty

 List<int> numbers= new List<int>();

If a collection is empty and you unknowingly try to find a specific element, then you will get a null reference error, to solve this problem, LINQ provides the second version of Element operators like FirstOrDefault(), LastOrDefault(), SingleOrDefault() etc.

In short, in LINQ, element operators are used to return a specific element from a collection , for example, with element operators, we can return first element , last element, element at any specific position or even a single element based on specific condition, from the given collection.

Linq provides us following Element operators
    • First
    • FirstOrDefault
    • Last
    • LastOrDefault
    • ElementAt
    • ElementAtOrDefault
    • Single
    • SingleOrDefault
    • DefaultIfEmpty

By using these element operators we can get a specific element from the collection. The following diagram shows more detailed information related to element operators.

Element Operators in LINQ
Element Operators in LINQ

In the coming chapters, we will discuss all these element operators in detail with examples. We will be studying each of them with a demo so that we can get a clear understating of these operators.