Element Operators In LINQ

Introduction

Here we will learn about Element Operators, their uses and various element operators. Let's move on with an example.

Prerequisite 

  • Visual Studio
  • Basics of LINQ

Article Flow

  • Element Operators and their uses
  • List Of Element Operators
  • Use Of ElementAt
  • Use of ElementAtOrDefault
  • Difference between ElementAt and ElementAtOrDefault
  • Use of First
  • Use of FirstOrDefault
  • Difference between First and FirstOrDefault
  • Use of Single
  • Use of SingleOrDefault
  • Difference between Single and SingleOrDefault
  • Use of Last
  • Use of LastOrDefault 
  • Difference between Last and LastOrDefault
  • Difference between all Element Operators 

Element Operators

Element operators are used to return a single value or a particular element from a collection(s).

Example

Just assume a number of people are traveling in a bus. When we ask who the driver of this bus is, there will be only one person. So, here, the number of people is a collection and the driver is a single result from that collection.  

List Of Element Operators

There are eight types of element operators in LINQ.

  1. ElementAt
  2. ElementAtOrDefault
  3. First
  4. FirstOrDefault
  5. Single
  6. SingleOrDefault
  7. Last 
  8. LastOrDefault

Use Of ElementAt

We know very well that "At" represents index in C# coding. Similarly, the ElementAt operator is used to get the element from a specific index in a given collection.

Before moving to the example, we create two lists - myFamilyMemAge list created using int type and myFamilyMemebers list created using string type.

List<int> myFamilyMemAge = new List<int>() { 48, 45, 31, 28, 26, 24 };  
List<string> myFamilyMemebers = new List<string>() { "Sekar L", "Sivagami Sekar", "Mohan Sekar", "Kumadha Sekar", "Gnanavel Sekar", null };  

Now, first we will try to get the first element from the collection using ElementAt Method. The ElementAt method starts from 0(Zero)th index too, like an array. So here, I will mention 0 as index to get the first element of the collection.

Console.WriteLine("1st Element in myFamilyMemAge: {0}", myFamilyMemAge.ElementAt(0)); 

Output

Okay, we got the result from that collection by specifying the index. In myFamilyMemAge list, there are 6 elements from 0 to 5. Now, let's try a value of the index. Try 6.

Console.WriteLine("6th Element in myFamilyMemAge: {0}", myFamilyMemAge.ElementAt(6));  

Output

OMG! We got the OutofRangeException. Finally, we got a clearer picture of ElementAt. It's used to get the element from a respective collection by specifying the index which should be in the element count.

Use Of ElementAtOrDefault

ElementAtOrDefault method is used to result out a specific element from the respective collection by specifying the specific index. Okay, we will move to the example to get a clear picture of this method. We will try the same that we did with ElementAt method.

Console.WriteLine("1st Element in myFamilyMemebers: {0}", myFamilyMemebers.ElementAtOrDefault(0));

Result

In myFamilyMemebers list, we have 6 elements and we got the first element by specifying index 0. Let's try the out of index element. I mean more than 5.

Console.WriteLine("6th Element in myFamilyMemebers: {0}", myFamilyMemebers.ElementAtOrDefault(6));

Result

For the string, it returns Empty string.  Let's try in int collection.

Console.WriteLine("6th Element in myFamilyMemebers: {0}", myFamilyMemAge.ElementAtOrDefault(6));

Result

Okay, now we got two things. ElementAtDefault returns two results -empty and zero when out of index value is used in string and integer collection respectively. If String doesn't exist, it returns string.empty and in case of integer collection out of index, it will return 0 (zero).

Oh! Here we are getting the empty string while we haven't had the element in index. Now, we got the clear picture of ElementAtOrDefault method in LINQ. Let's now list out the use functionality of ElementAt and ElementAtOrDefault to know the difference.

Difference between ElementAt and ElementAtOrDefault

 ElementAt  ElementAtOrDefault

 Returns the Element at specific index from a collection.

ex:

Console.WriteLine("1st Element in myFamilyMemAge: {0}", myFamilyMemAge.ElementAt(0)); 

 Returns the Element at specific Index from a collection.

ex:

Console.WriteLine("1st Element in myFamilyMemebers: {0}", myFamilyMemebers.ElementAtOrDefault(0)); 

 Throws ArgumentOutOfRange Exception in case of specific index out of range.

 Returns a default value in case the specific index is out of range.

Default Value 

For String-> Null

For Int-> 0(Zero) 

Use Of First 

Returns the first element from a respective collection or the first element, satisfying a specific condition. Let's move to the example to get a clearer picture.

First() Overloads following two methods

public static TSource First<TSource>(this IEnumerable<TSource> source);
public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

public static TSource First<TSource>(this IEnumerable<TSource> source)

This method doesn't take any input parameter(s) and returns only one element from the respective collection. Here is an example to get the clear picture.

Example

Console.WriteLine("First => 1st Element in myFamilyMemebers: {0}", myFamilyMemebers.First()); 

Result

Okay! we got the first element from the collection without specifying any condition. Now, let's try with some conditions.

We knew very well, 5 records contain with "s" character.

If it contains a null value it will throw the null reference exception, so I am going to remove the 5th element "Null" from myFamilyMembers list

myFamilyMemebers.RemoveAt(5);

Now, proceed with contains:

var scontains = myFamilyMemebers.Where(a => a.ToLower().Contains("s")).ToList();  

 

public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate); 

This method will take input parameter(s) and return only one record from respective collection, if it's failed to satisfy specific condition it will throw error's. Shall we move to the example

Console.WriteLine("First => 1st Element in myFamilyMemebers: {0}", myFamilyMemebers.First(a => a.ToLower().Contains("s")));  

 

Now let's see the unsatisified condition with the first keyword, we knew very well z character doesn't contain in any records

Console.WriteLine("First => 1st Element in myFamilyMemebers: {0}", myFamilyMemebers.First(a =>a.ToLower().Contains("z"))); 

Okay, now we got the clear picture about First Keyword in linq, the first keyword used to get the first element from respective collection by with condition or without condition, it will throw an error in case the specified condition is not succeed.

Use Of FirstOrDefault

FirstOrDefault also same like "First" to return the first element from respective collection, okay we will see step by step to find the unique functionality.

FirstOrDefault Method Overloads following two methods

public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source);
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source);

This method doesn't take any input parameter and returns single element from respective collection. shall we see the example to get clear picture about this.

Console.WriteLine("FirstOrDefault => 1st Element in myFamilyMemebers: {0}", myFamilyMemebers.FirstOrDefault());  

Now Let's see the result

public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

This method takes the lambda expression as predicate delegate to specify condition and returns the first element that satisfies the specified condition.

Now Let's try with some condition in FirstOrdefault, here am just checking which record contains "o".

Console.WriteLine("FirstOrDefault => 1st Element in myFamilyMemebers: {0}",  
myFamilyMemebers.FirstOrDefault(a=>a.ToLower().Contains("o")));

Now run and see the result, we have only one record containing "o" in the row.

Okay, now we shal try with an un-satisfied condition, we already seen in First() the "z" character doesn't contain an anyrecord, Now we will try the same with FirstOrDefault.

Console.WriteLine("FirstOrDefault => 1st Element in myFamilyMemebers: {0}", myFamilyMemebers.FirstOrDefault(a => a.ToLower().Contains("z")));  

Now run and see the result.

We got an empty string without an exception, now we have a clear picture about FirstOrDefault, it's used to get the first element with or without condition from the respective collection and it will handle null value exceptions whenever it falls into null value exception it will throw the empty value without exception.

Difference between First and FirstOrDefault  

First FirstOrDefault

Returns the first element from respective collection

ex:

Console.WriteLine("First => 1st Element in myFamilyMemebers: {0}", myFamilyMemebers.First());

Returns the first element from respective collection

ex:

Console.WriteLine("FirstOrDefault => 1st Element in myFamilyMemebers: {0}", myFamilyMemebers.FirstOrDefault());

Throws invalidOperationException in case of it's failed with condition

ex:

Console.WriteLine("First => 1st Element in myFamilyMemebers: {0}", myFamilyMemebers.First(a => a.ToLower().Contains("z"))) 

Returns Null in case it's failed with condition

ex:

Console.WriteLine("FirstOrDefault => 1st Element in myFamilyMemebers: {0}", myFamilyMemebers.FirstOrDefault(a => a.ToLower().Contains("z"))); 

Use Of Single

Returns the lone element from the collection and the lone element that satisfies a certain condition. We already saw elementAt; First to get the first element from respective collection, then what's the use of Single?.

We should use AT if you expect a collection to contain only one item, or the query should give the one record. If Single() found no elements or more than one element in the collection then throws InvalidOperationException

"Single" overloads following 2methods

public static TSource Single<TSource>(this IEnumerable<TSource> source);
public static TSource Single<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

public static TSource Single<TSource>(this IEnumerable<TSource> source);

This method doesn't take any input parameter and it return single element from the respective collection. We shall move to the example to get clear picture about this:

Console.WriteLine("Single =>single Element in myFamilyMemebers: {0}", myFamilyMemebers.Single()); 

Now run this and see the result; Uh oh, we got the exception because the specified collection(list) contains more than one element, the single is used to return only one element which query return only one result.

Shall we try with integer collection:

Console.WriteLine("Single => single Element in myFamilyMemebers: {0}", myFamilyMemAge.Single());

Now run and see the result, we get the same exception:

Shall we try with an empty collection, for that create list as shown below:

List<string> emptylist = new List<string>();  
Console.WriteLine("Single => single Element in myFamilyMemebers: {0}", emptylist.Single());  

Now run and see the result, here we getting the sequence contains no element exception:

Now we got the clear knowledge about this method.

public static TSource Single<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

This method takes the lambda expression as a predicate delegate that specifies the condition and returns a single element that satisfies the specified condition. Shall we see the example

Console.WriteLine("Single =>single Element in myFamilyMemebers: {0}", myFamilyMemebers.Single(a=>a.StartsWith("G")));

Here I am passing the input parameter startswith "G" character, now run and see the result. In this result myFamilyMembers has only one record that starts with "G." 

In case no element is present in the respective collection, it will throw a sequence containing no value and now we got the clear picture about using the single.

SingleOrDefault

SingleOrDefault also provides the same result as a single method. The difference is, it returns a default value of a specified generic type, instead of throwing an exception if no element found for the specified condition.Although, it will throw InvalidOperationException if it is found, more than one element for the specified condition in the collection.

"SingleOrDefault" overloads following methods

public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source);
public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

Detailed Description

public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source);-> Doesn't take any input parameter's and it's same as Single

public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate); -> It takes input parameter and returns a single record if it satisfies the condition, otherwise it will return the default value of specified generic type.

Shall we try with an unsatisfied condition to check this unique functionality

Console.WriteLine("SingleOrDefault =>single Element in myFamilyMemebers: {0}", myFamilyMemebers.SingleOrDefault(a => a.StartsWith("z")));

Now run and see the result:

Here we got the null value because the type is a string, if the collection value type is string it will return 0. Now we got the clear picture about singleOrDefault. It's used to return the single record with the satisfied or unsatisfied condition and it will throw an error if the result brings more than one element.

Difference between Single and SingleOrDefault

Single SingleOrDefault

Returns only one element from a collection, or the only element that satisfies a condition

ex:

Console.WriteLine("Single =>single Element in myFamilyMemebers: {0}", myFamilyMemebers.Single(a => a.StartsWith("G"))); 

Returns only one element from a collection or the only one element that satisfies a condition or bring the empty result

ex:

Console.WriteLine("SingleOrDefault =>single Element in myFamilyMemebers: {0}", myFamilyMemebers.SingleOrDefault(a => a.StartsWith("z")));

return InvalidOperationException in case of sequence contain no element

it returns a default value of a specified generic type, instead of throwing an exception if no element found for the specified condition.

Use of Last

It returns last elements from respective collection or last element from the respective collection based on matching criteria,

"Last " Overloads following methods:

public static TSource Last<TSource>(this IEnumerable<TSource> source);
public static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)

public static TSource Last<TSource>(this IEnumerable<TSource> source);

This method doesn't take any input parameter's, or the last element that satisfies the specified condition using lambda expression or Func delegate. If a given collection is empty or does not include any element that satisfied the condition then it will throw InvalidOperation exception.

Shall we move to the example to get clear idea:

Console.WriteLine("Last=>Last Element in myFamilyMemAge: {0}", myFamilyMemAge.Last());

Now run and see the result:

Here, we have list record's from that respective collection, so that we got the result, just assume we doesn't have any record/element in respective collection

List<string> emptylist = new List<string>();  
Console.WriteLine("Last=>Last Element in myFamilyMemAge: {0}", emptylist.Last());  

Now run and see the result

Oh! here we getting sequence contains no elements exception because of there is no element present that emptylist collection.

public static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)

It will allow the user to pass the input parameter(s) and return the last element from respective collection, it will fire the invalidoperationexception incase the query returns the 0 result from respective collection with respective condition.

Console.WriteLine("Last=>Last Element in myFamilyMemAge: {0}", myFamilyMemAge.Last(a => a > 40));  

Now run and see the result, here we mentioned the condition is greater than 40, so we have two record are 48 and 45, the last record is 45, so we getting the result 45 as last record.

if am mention unsatisfy condition as below, it will throw the invalidoperationexception

Console.WriteLine("Last=>Last Element in myFamilyMemAge: {0}", myFamilyMemAge.Last(a => a > 50));   

Now we got the clear picture about Last, it's used to return the last element from respective collection and it will throw the invalidoperationexception incase the query returns null.

Use of LastOrDefault

The LastOrDefault also Work same as Last, The only difference is that it returns default value of the data type of a collection if a collection is empty or doesn't find any element that satisfies the condition.

"LastOrDefault " Overloads following methods

public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source);
public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)

public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source);

It doesn't allow the input parameter's and return's the last element from the respective collection, and it returns default value of data type of collection if a collection is empty or specified condition is not satisified.

Let's move to the example

Console.WriteLine("LastOrDefault=>Last Element in myFamilyMemAge: {0}", myFamilyMemAge.LastOrDefault());

Now run and see the result

Now let's move with empty List example

List<string> emptylist = new List<string>();  
Console.WriteLine("LastOrDefault=>Last Element in emptylist: {0}", emptylist.LastOrDefault());  

now run and see the result

Now we got the clear picture about LastOrDefault , it returns the last element from the respective collection, if the condition is not satisfied it will return the default value based on the collection type.

public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) 

It accepts input parameter(s) and returns the last element from a collection and it returns default value in case if no element found in collection, We knew very well no one is above 50age from myFamilyMemAge collection, Let us try with that  

Console.WriteLine("Last=>Last Element in myFamilyMemAge: {0}", myFamilyMemAge.Last(a => a > 50));

Now run and see the result

Yes! we got the empty result as default value because no record found with more than 50 age 

Difference between Last and LastOrDefault

Last LastOrDefault

It returns last elements in sequence or last element from the list based on matching criteria

ex:

Console.WriteLine("Last=>Last Element in myFamilyMemAge: {0}", myFamilyMemAge.Last(a => a > 40)); 

Returns the last element from a collection and it returns default value in case if no element found in collection

ex:

Console.WriteLine("LastOrDefault=>Last Element in emptylist: {0}", emptylist.LastOrDefault()); 

InvalidOperationException in case of sequence contain no element

it returns a default value of a specified generic type, instead of throwing an exception if no element found for the specified condition.

Difference between all Element Operators

  • ElementAt - It returns an element from the respective collection based on specified index position
  • ElementAtOrDefault -  Its same as ElementAt but it returns default value in case if no element present at specified index of respective collection
  • Single - It returns single specific element from respective collection
  • SingleOrDefault - Its same as Single but it returns default value in case if no element found from respective collection
  • First - It returns first element in sequence or first element from the resoectuve collection based on specified condition
  • FirstOrDefault - Its same as First but it returns default value in case if no element found in collection
  • Last - It returns last elements in sequence or last element from the respective collection based on matching criteria
  • LastOrDefault - Returns the last element from respective collection and it returns default value in case if no element found from respective collection

Summary 

In this article we learned how to use the ElementAt, ElementAtOrDefault, First, FirstOrDefault, Single, SingleOrDefault, Last and LastOrDefault, and their differences.

I hope this article will help you, your valuable feedback and comments are always welcome.


Similar Articles