LINQ Extension Methods Quantifier And Aggregation Operator - Part Two

This article is continuation of Linq extension methods. If you want to read first part please click here Part One. In this article I will demonstrate quantifier operator and aggregation operators.

This article is a continuation of LINQ extension methods article Part One. In this article, I will demonstrate quantifier operators and aggregation operators.

Linq extension methods Quantifier and Aggregation operator
Let's see the examples first. 
  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. };    
  45. List < Department > deparmentList = new List < Department > () {    
  46.     new Department() {    
  47.             DepartmentId = 101, DepartmentName = "IT"    
  48.         },    
  49.         new Department() {    
  50.             DepartmentId = 102, DepartmentName = "HR"    
  51.         },    
  52.         new Department() {    
  53.             DepartmentId = 103, DepartmentName = "Account"    
  54.         },    
  55. };    
  1.   Console.WriteLine("|================= All Operator ===============|");  
  2.   
  3.   Console.WriteLine("\n");  
  4.   var resultAllOperator = employeeList.All(emp => emp.DepartmentId >= 101 && emp.DepartmentId <= 104);  
  5.   
  6.   Console.WriteLine("All the elements satisfy a condition : " + resultAllOperator);  
  7.   
  8.   var resultAllOperatorWithFalse = employeeList.All(emp => emp.DepartmentId >= 101 && emp.DepartmentId <= 102);  
  9.   
  10.   Console.WriteLine("One or more elements not satisfy a condition  : " + resultAllOperatorWithFalse);  
  11.   
  12.   Console.WriteLine("\n");  

 

Linq extension methods Quantifier and Aggregation operator

 

In the first example, I have used the All Operator on employee list and checked condition for employee id between 101 and 104. In the above list, all employees fall under given condition so all operators return True.

In the second example, I have used the All Operator on the same list but changes made to condition which is not satisfying for employee name with James because he belongs to department 103. So this time, All operator returns False.
  1.  Console.WriteLine("|================= Any Operator ===============|");  
  2.   
  3.  Console.WriteLine("\n");  
  4.   
  5.  var resultAnyOperatorWithTrue = employeeList.Any(emp => emp.Name == "Kumar");  
  6.   
  7.  Console.WriteLine("At least one element satisfy a condition : " + resultAnyOperatorWithTrue);  
  8.   
  9.  var resultAnyOperatorWithFalse = employeeList.Any(emp => emp.Name == "JigneshKumar");  
  10.   
  11.  Console.WriteLine("No element satisfy a condition : " + resultAnyOperatorWithFalse);  

 

Linq extension methods Quantifier and Aggregation operator

 

In the above example, I have used the Any operator on employee list, with the condition on employee name and the given condition which satisfies the condition so that the Any operator returns True.

In the second example, we have given the same condition with different values for which no employee has the same name, so the Any operator will return False.
  1. Console.WriteLine("|================= Conatains Operator ===============|");  
  2.   
  3. Console.WriteLine("\n");  
  4.   
  5.   
  6. Employee employee = new Employee()  
  7.   {  
  8.      EmployeeId = 1003,  
  9.      Name = "Kumar",  
  10.      DepartmentId = 101,  
  11.      skills = new List<string> { ".Net""SQL""API" }  
  12.   };  
  13.   
  14. var resultContainWithTrue = employeeList.Contains(employee, new EmployeeComparer());  
  15.   
  16. Console.WriteLine("Conatain Operator compare with actual values of an object :" + resultAnyOperatorWithTrue);  
  17.   
  18. var resultContainWithFalse = employeeList.Contains(employee);  
  19.   
  20. Console.WriteLine("Conatain Operator compares only reference of an object :" + resultAnyOperatorWithFalse);  
  1. class EmployeeComparer : IEqualityComparer<Employee>    
  2. {    
  3.   public bool Equals(Employee x, Employee y)    
  4.         {    
  5.             if (x.EmployeeId == y.EmployeeId &&    
  6.                 x.Name.ToLower() == y.Name.ToLower() &&    
  7.                 x.DepartmentId == y.DepartmentId &&    
  8.                 x.skills == y.skills)    
  9.                 return true;    
  10.     
  11.             return false;    
  12.         }    
  13.     
  14.         public int GetHashCode(Employee obj)    
  15.         {    
  16.             return obj.GetHashCode();    
  17.         }    
  18.     }    

 

Linq extension methods Quantifier and Aggregation operator

 

In the above example, I have used the Contain operator to check if a given element exists in the collection or not. If the element exists, then it will return True; else False.
  • One thing to note in the above example is that the Contain extension method works fine with primitive data types like int, string etc. but if you want to check for custom class, then you need to implement IEqualityCompare to check to object and compare actual values of the object.

  • In the second part of the above snippet, I have used the Contain method to check with employee object which has some data with one of the employee list elements but still, it is returning false because Contain checks on the reference of an object.

 

Linq extension methods Quantifier and Aggregation operator

 

Aggregate operators are used to perform mathematical operations, like sum, average, count, or min or max on numeric values from a collection.

One thing to note about Aggregate operator is that we can use this operator in only the method syntax, however, it is not valid in query syntax. 
  1. Console.WriteLine("|================= Aggregate Operator ===============|");  
  2.   
  3. Console.WriteLine("\n");  
  4.   
  5. var resultAggregate = employeeList.Aggregate<Employee, string>  
  6.                      ("Name of Employee comma Separated : ", (emp, str) => emp += str.Name + ", ");  
  7. Console.WriteLine(resultAggregate.Remove(resultAggregate.Length-2));  
  8. Console.WriteLine("\n");  

Linq extension methods Quantifier and Aggregation operator 

Aggregate extension method is used for custom aggregation. In the above example, I have listed employee name with comma separated values from the collection using the Aggregate method. 
  1. List<int> intList = new List<int>() { 100, 111, 167, 200, 222, 300, 400, 500, 600, 700, 800, 900 };  
  2.   
  3. Console.WriteLine("\n");   
  1. Console.WriteLine("|================= Average Operator ===============|");  
  2.              
  3. Console.WriteLine("\n");  
  4. var resultAverage = intList.Average();  
  5. Console.WriteLine("Average of all element is :" + resultAverage);  
  6. Console.WriteLine("\n");  
Linq extension methods Quantifier and Aggregation operator

Let's take an example where I need to caculate the average of all numeric vaules in a list. I can use the average extenstion method to find the average of the list or the collection which contains numeric values.
  1. Console.WriteLine("|================= Count Operator ===============|");  
  2. Console.WriteLine("\n");  
  3. var resultCount = intList.Count();  
  4. Console.WriteLine("Totat number of Element in list :" + resultCount);  
  5.   
  6. var resultOfEvenNumberCount = intList.Count(i=> i%2==0);  
  7. Console.WriteLine("count of Even Element in list :" + resultOfEvenNumberCount);  
  8. Console.WriteLine("\n");  
Linq extension methods Quantifier and Aggregation operator 
 
Count operator is used for finding the number of elements in a colletion.

In the above example, I used Count for two purposes - first, it returns the total number of elements in a list and second, it returns the number of Count for even numbers. 
  1. Console.WriteLine("|================= Max Operator ===============|");  
  2. Console.WriteLine("\n");  
  3. var resultMax = intList.Max();  
  4. Console.WriteLine("Maximum number in List :" + resultMax);  
Linq extension methods Quantifier and Aggregation operator

Max method will return the largest element from the numeric collection. In the above example, it returns maximum value from int list which is 900.
  1. Console.WriteLine("|================= Min Operator ===============|");  
  2.   
  3. Console.WriteLine("\n");  
  4. var resultMin = intList.Min();  
  5. Console.WriteLine("Minimum number in List :" + resultMin);  
  6. Console.WriteLine("\n");  
Linq extension methods Quantifier and Aggregation operator

Min extension method will return the smallest element from the numeric collection. In the above example, it returns minimum value from int list which is 100. 
  1. Console.WriteLine("|================= Sum Operator ===============|");  
  2.   
  3. Console.WriteLine("\n");  
  4. var resultSum = intList.Sum();  
  5. Console.WriteLine("Sum of number in List :" + resultSum);  
  6.   
  7. Console.WriteLine("\n");  
  8.   
  9. var resultSumofEvenNumber = intList.Sum(s => { if (s%2 == 0) return s; return 0; });  
  10. Console.WriteLine("Sum of Evem number in List :" + resultSumofEvenNumber);  
  11. Console.WriteLine("\n");  
Linq extension methods Quantifier and Aggregation operator
  • Sum method will return the sum of all elements from the collection. In the above example, I have used the sum method for two different purposes.
  • First one will return the sum of all elements from int List. Here the sum of all elements is 5000.
  • Second will return the sum of even number from int List . Here, the even numbers' sum is 4722.  
Conclusion

Linq provides many extension methods to achieve various  functionality. Here I have demostrated quantifier operator and aggregation operators. Quantifier operators are used for the evaluate elements in the collection based on specified condtions;  if all or some of them satisfy the condition then it will return the boolean value true, else it will return false. Aggregation operators are used to perform a mathematical operation on numeric values in the collection.

If you want to read more articles on other topics:
Happy Learning!

Thank you for reading..