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.
- List < Employee > employeeList = new List < Employee > () {
- new Employee() {
- EmployeeId = 1001, Name = "Rajwal", DepartmentId = 101, skills = new List < string > {
- ".Net",
- "MVC",
- "Agular"
- }
- },
- new Employee() {
- EmployeeId = 1002, Name = "Jay", DepartmentId = 101, skills = new List < string > {
- ".Net",
- "Java",
- "JQuery"
- }
- },
- new Employee() {
- EmployeeId = 1003, Name = "Kumar", DepartmentId = 101, skills = new List < string > {
- ".Net",
- "SQL",
- "API"
- }
- },
- new Employee() {
- EmployeeId = 1004, Name = "Alok", DepartmentId = 102, skills = new List < string > {
- ".Net",
- "MVC",
- "Agular"
- }
- },
- new Employee() {
- EmployeeId = 1005, Name = "Shan", DepartmentId = 102, skills = new List < string > {
- ".Net",
- "Python",
- "Linq"
- }
- },
- new Employee() {
- EmployeeId = 1006, Name = "James", DepartmentId = 103, skills = new List < string > {
- ".Net",
- "MVC",
- "Agular"
- }
- }
- };
- Console.WriteLine("|================= ElementAt==================!");
- Console.WriteLine("\n");
-
- Console.WriteLine("1st Element in employee list :" +
- "Employee Id : " + employeeList.ElementAt(0).EmployeeId +
- "Employee Name : " + employeeList.ElementAt(0).Name);
- Console.WriteLine("|================= ElementAt==================!");
- Console.WriteLine("\n");
-
- Console.WriteLine("1st Element in employee list :" +
- "Employee Id : " + employeeList.ElementAt(6).EmployeeId +
- "Employee Name : " + employeeList.ElementAt(6).Name);
- Console.WriteLine("|================= ElementAt==================!");
- Console.WriteLine("\n");
-
- Var resultElementAtOrDefault = employeeList.ElementAtOrDefault(6);
-
- Console.WriteLine("Element in employee list :" + resultElementAtOrDefault);
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.
- Console.WriteLine("|================= Single ==================!");
- Console.WriteLine("\n");
-
- var resultSingle = employeeList.Single(e => e.EmployeeId == 1001);
-
- Console.WriteLine("Single employee in employee list :" + "Employee Name : " + resultSingle.Name );
- Console.WriteLine("|================= Single With no elment found ==================!");
- Console.WriteLine("\n");
-
- var resultSingle = employeeList.Single(e => e.EmployeeId == 1008);
-
- Console.WriteLine("Single employee in employee list :" + "Employee Name : " + resultSingle.Name );
- Console.WriteLine("|================= Single With no elment found ==================!");
- Console.WriteLine("\n");
-
- var resultSingleOrDefault = employeeList.SingleOrDefault(e => e.EmployeeId == 1008);
-
- Console.WriteLine("Single employee in employee list :" + resultSingleOrDefault);
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.
- Console.WriteLine("|================= First==================!");
- Console.WriteLine("\n");
-
- var resultFirst = employeeList.First(e => e.EmployeeId == 1001);
- Console.WriteLine("1st Element in employee list :" + "Employee Id : " + resultFirst.EmployeeId + " Name : " + resultFirst.Name);
- Console.WriteLine("|================= FirstOrDefault ==================!");
- Console.WriteLine("\n");
-
- var resultFirst = employeeList.FirstOrDefault(e => e.EmployeeId == 1007);
-
- Console.WriteLine("Element in employee list :" + resultFirst);
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.
- Console.WriteLine("|================= Last ==================!");
- Console.WriteLine("\n");
-
- var resultLast = employeeList.Last();
-
- Console.WriteLine("Last Element in employee list :" + resultLast.Name);
- Console.WriteLine("|================= Last ==================!");
- Console.WriteLine("\n");
-
- var resultLast = employeeList.Last(e =>e.EmployeeId == 1008);
-
- Console.WriteLine("Last Element in employee list :" + resultLast.Name);
- Console.WriteLine("|================= LastOrDefault ==================!");
- Console.WriteLine("\n");
-
- var resultLast = employeeList.LastOrDefault(e => e.EmployeeId == 1008);
-
- Console.WriteLine("Last Element in employee list :" + resultLast);
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.
- Console.WriteLine("|========== Distinct Fruit ===========|");
-
- List<string> fruitList = new List<string>() { "Mango", "Apple", "Strawbarry", "Bluebarry", "Kiwi", "Gauva", "Apple", "Mango"};
-
- var resultDistinct = fruitList.Distinct();
- foreach (var item in resultDistinct)
- {
- Console.WriteLine(item);
- }
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.
- Console.WriteLine("|========== Union of Two Fruit List ===========|");
- List<string> SeasonalfruitList= new List<string>(){"Banana","Graps", Apple", "Mango"};
-
- var resultUnion = fruitList.Union(SeasonalfruitList);
- foreach (var item in resultUnion)
- {
- Console.WriteLine(item);
-
- }
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.
- Console.WriteLine("|========== Intersect of Two Fruit List ===========|");
-
- var resultIntersect = fruitList.Intersect(SeasonalfruitList);
- foreach (var item in resultIntersect)
- {
- Console.WriteLine(item);
- }
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.
- Console.WriteLine("|========== Except of Two Fruit List ===========|");
-
- var resultExcept = fruitList.Except(SeasonalfruitList);
- foreach (var item in resultExcept)
- {
- Console.WriteLine(item);
- }
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.