LINQ Extension Methods - Element Operator And Set Operator - Part Three

This article is the continuation of the LINQ extension method. If you have missed the earlier part of LINQ extension method please visit the first two parts here,

In this article, we are going to explore two more operators  --  element operator and set operator. Element operators are used for returning a particular element from the collection and set operators include distinct, except, intersect and union, which are used to get a unique element or all elements from a single collection or multiple collections based on a specific condition or based on our requirements.

I have chosen employee collections which have properties like employeeId, Name of City, and skills. Let us have a practical example of how to use element operator on collection.

  1. List < Employee > employeeList = new List < Employee > () {      
  2.     new Employee() {      
  3.             EmployeeId = 1001, Name = "Rajwal", DepartmentId = 101, skills = new List < string > {      
  4.                 ".Net",      
  5.                 "MVC",      
  6.                 "Agular"      
  7.             }      
  8.         },      
  9.         new Employee() {      
  10.             EmployeeId = 1002, Name = "Jay", DepartmentId = 101, skills = new List < string > {      
  11.                 ".Net",      
  12.                 "Java",      
  13.                 "JQuery"      
  14.             }      
  15.         },      
  16.         new Employee() {      
  17.             EmployeeId = 1003, Name = "Kumar", DepartmentId = 101, skills = new List < string > {      
  18.                 ".Net",      
  19.                 "SQL",      
  20.                 "API"      
  21.             }      
  22.         },      
  23.         new Employee() {      
  24.             EmployeeId = 1004, Name = "Alok", DepartmentId = 102, skills = new List < string > {      
  25.                 ".Net",      
  26.                 "MVC",      
  27.                 "Agular"      
  28.             }      
  29.         },      
  30.         new Employee() {      
  31.             EmployeeId = 1005, Name = "Shan", DepartmentId = 102, skills = new List < string > {      
  32.                 ".Net",      
  33.                 "Python",      
  34.                 "Linq"      
  35.             }      
  36.         },      
  37.         new Employee() {      
  38.             EmployeeId = 1006, Name = "James", DepartmentId = 103, skills = new List < string > {      
  39.                 ".Net",      
  40.                 "MVC",      
  41.                 "Agular"      
  42.             }      
  43.         }      
  44. };      
LINQ Extension Methods - Element Operator And Set Operator
  1. Console.WriteLine("|================= ElementAt==================!");  
  2. Console.WriteLine("\n");  
  3.   
  4. Console.WriteLine("1st Element in employee list :" + 
  5.                   "Employee Id : " + employeeList.ElementAt(0).EmployeeId + 
  6.                   "Employee Name : " employeeList.ElementAt(0).Name);  
 LINQ Extension Methods - Element Operator And Set Operator
  1. Console.WriteLine("|================= ElementAt==================!");    
  2. Console.WriteLine("\n");    
  3.     
  4. Console.WriteLine("1st Element in employee list :" +   
  5.                   "Employee Id : " + employeeList.ElementAt(6).EmployeeId +   
  6.                   "Employee Name : " + employeeList.ElementAt(6).Name);   
 LINQ Extension Methods - Element Operator And Set Operator
  1. Console.WriteLine("|================= ElementAt==================!");      
  2. Console.WriteLine("\n");      
  3.   
  4. Var resultElementAtOrDefault =  employeeList.ElementAtOrDefault(6);  
  5.       
  6. Console.WriteLine("Element in employee list :" +  resultElementAtOrDefault);    
LINQ Extension Methods - Element Operator And Set Operator  

ElementAt and ElementAtOrDefault do the same thing, but ElementAtOrDefault will not throw an error if there is no element at the specified index. It will return the default value for that collection. In the above example ElementAt(6) is throwing the error in the first snippet but ElementAtOrDefault(6) is not throwing any error --  it returns an empty collection in the second snippet. 

LINQ Extension Methods - Element Operator And Set Operator  
  1. Console.WriteLine("|================= Single ==================!");  
  2. Console.WriteLine("\n");  
  3.   
  4. var resultSingle = employeeList.Single(e => e.EmployeeId == 1001);  
  5.   
  6. Console.WriteLine("Single employee in employee list :" + "Employee Name : " + resultSingle.Name );  
 LINQ Extension Methods - Element Operator And Set Operator 
  1. Console.WriteLine("|================= Single With no elment found ==================!");    
  2. Console.WriteLine("\n");    
  3.     
  4. var resultSingle = employeeList.Single(e => e.EmployeeId == 1008);    
  5.     
  6. Console.WriteLine("Single employee in employee list :" + "Employee Name : " + resultSingle.Name );     
LINQ Extension Methods - Element Operator And Set Operator 
  1. Console.WriteLine("|================= Single With no elment found ==================!");      
  2. Console.WriteLine("\n");      
  3.       
  4. var resultSingleOrDefault = employeeList.SingleOrDefault(e => e.EmployeeId == 1008);      
  5.       
  6. Console.WriteLine("Single employee in employee list :" + resultSingleOrDefault);        
LINQ Extension Methods - Element Operator And Set Operator  

Single and SingleOrDefault do the same thing but the only difference is SingleOrDefault will not throw an error if there is no element in the collection and it returns a null value. In the above example, we are able to see a default error thrown for employeeId =1008 but SingleOrDefault is returning default value as null for employeeId=1008 inup the collection.

LINQ Extension Methods - Element Operator And Set Operator
  1. Console.WriteLine("|================= First==================!");  
  2. Console.WriteLine("\n");  
  3.   
  4. var resultFirst = employeeList.First(e => e.EmployeeId == 1001);  

  5. Console.WriteLine("1st Element in employee list :" + "Employee Id : " + resultFirst.EmployeeId + " Name : " + resultFirst.Name);  
LINQ Extension Methods - Element Operator And Set Operator 
 
LINQ Extension Methods - Element Operator And Set Operator 
  1. Console.WriteLine("|================= FirstOrDefault ==================!");  
  2. Console.WriteLine("\n");  
  3.   
  4. var resultFirst = employeeList.FirstOrDefault(e => e.EmployeeId == 1007);  
  5.   
  6. Console.WriteLine("Element in employee list :" + resultFirst);  
 LINQ Extension Methods - Element Operator And Set Operator
 
First and FirstOrDefault do the same thing but the only difference is FirstOrDefault will not throw the error if there is no element in the collection and returns the default value. In the above example, we are able to see a default error thrown for employeeId =1007 but SingleOrDefault is returning default value as null for employeeId=1007 the collection. 
 
LINQ Extension Methods - Element Operator And Set Operator 
  1. Console.WriteLine("|================= Last ==================!");  
  2.            Console.WriteLine("\n");  
  3.   
  4.            var resultLast = employeeList.Last();  
  5.   
  6.            Console.WriteLine("Last Element in employee list :" + resultLast.Name);  
LINQ Extension Methods - Element Operator And Set Operator 
  1. Console.WriteLine("|================= Last ==================!");  
  2. Console.WriteLine("\n");  
  3.   
  4. var resultLast = employeeList.Last(e =>e.EmployeeId == 1008);  
  5.   
  6. Console.WriteLine("Last Element in employee list :" + resultLast.Name);  
LINQ Extension Methods - Element Operator And Set Operator 
  1. Console.WriteLine("|================= LastOrDefault ==================!");  
  2.            Console.WriteLine("\n");  
  3.   
  4.            var resultLast = employeeList.LastOrDefault(e => e.EmployeeId == 1008);  
  5.   
  6.            Console.WriteLine("Last Element in employee list :" + resultLast);   
LINQ Extension Methods - Element Operator And Set Operator 
 
Last and LastOrDefault do the same thing but the only difference is LastOrDefault will not throw the error if there is no element in the collection and it returns a default value. In the above example, we are able to see a default error thrown for employeeId =1008 but LastOrDefault is returning default value as null for employeeId=1007 in the collection.   
 
 LINQ Extension Methods - Element Operator And Set Operator
  1. Console.WriteLine("|========== Distinct Fruit ===========|");  
  2.   
  3. List<string> fruitList = new List<string>() { "Mango""Apple""Strawbarry""Bluebarry""Kiwi""Gauva""Apple""Mango"};  
  4.   
  5. var resultDistinct = fruitList.Distinct();  
  6.     foreach (var item in resultDistinct)  
  7.     {  
  8.       Console.WriteLine(item);                    
  9.     }  
LINQ Extension Methods - Element Operator And Set Operator  

Look at the above fruit list in the example above -- we have the fruit name for Apple and Mango twice. I have used distinct to remove duplicates from the fruit list and you are able to see output window with unique values from the fruit list and how distinct removed Apple and Mango from the list. 

  1. Console.WriteLine("|========== Union of Two Fruit List ===========|");  
  2. List<string> SeasonalfruitList= new List<string>(){"Banana","Graps", Apple", "Mango"};
  3.   
  4. var resultUnion = fruitList.Union(SeasonalfruitList);  
  5.     foreach (var item in resultUnion)  
  6.      {  
  7.        Console.WriteLine(item);  
  8.   
  9.      }  
LINQ Extension Methods - Element Operator And Set Operator 
 
Union combines multiple collections in a single collection without duplicate values. In the above example, Mango and Apple exist in both collections but in our put window we are able to see it only once because union performs a duplicate check and if it finds any duplicate then it removes it from the result set. 
  1. Console.WriteLine("|========== Intersect of Two Fruit List ===========|");  
  2.   
  3. var resultIntersect = fruitList.Intersect(SeasonalfruitList);  
  4.     foreach (var item in resultIntersect)  
  5.     {  
  6.        Console.WriteLine(item);  
  7.     }   
LINQ Extension Methods - Element Operator And Set Operator 
 
Intersect returns common elements from multiple collections into a single collection. In the above example, we have only two fruits in common in both collections so it will return only Mango and Apple.
  1. Console.WriteLine("|========== Except of Two Fruit List ===========|");  
  2.   
  3. var resultExcept = fruitList.Except(SeasonalfruitList);  
  4.     foreach (var item in resultExcept)  
  5.     {  
  6.        Console.WriteLine(item);  
  7.     }  
 LINQ Extension Methods - Element Operator And Set Operator

In the above example, Mango and Apple are part of the first and second lists, so except removes Mango and Apple from the final result set which we are able to see in the output window.


Similar Articles