LINQ Extension Methods - Part One

This article explains linq extension methods like filtering, grouping and sorting and projection orators

Linq provides standard query operators like filtering, sorting, grouping, aggregation, and concatenations, and it has many operators to achive many types of functionalities, which are called extension methods, in LINQ. 

In this article I will cover a few of them because it has many, and I will come up with part two very soon. Here I will explains LINQ standard query operators like projection, filtering, grouping, and sorting.  

LINQ
Let's see with a small example for all of the above operators. To explain LINQ queries I have created two lists, one is a list of employees and the other is a list of departments,  so we can write our query to understand all operators. We can use the database as well to get values from tables, but to make it simple I have created two lists with static data which we will use in our examples.

Projection Operator

Select and selectMany are projection operators.
  • Select operator is used to fetch values from collections, and selectMany operator is used for fetching values from collections of a collection.

  • The first example is for select operator where I have used select operator to fetch employee id and employee name from employee list.

  • The second example is for selectMany where I have used the selectMany operator for fetching skills belonging to employees where skills are listed inside employee class. It means selectMany returns values from lists inside a list. 
    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 = "Jmaes", 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. };  
    56. Console.WriteLine("======================= Select Operator ===============");  
    57. var selectResult = from emp in employeeList  
    58. select emp;  
    59. foreach(var item in selectResult) {  
    60.     Console.WriteLine("Employee ID :" + item.EmployeeId + "Name :" + item.Name);  
    61. }  
    62. Console.WriteLine("======================= SelectMany Operator ===============");  
    63. var resuleSelectMany = employeeList.SelectMany(emp => emp.skills);  
    64. foreach(var item in resuleSelectMany) {  
    65.     Console.WriteLine(item);  
    66. }  
LINQ 
 
Filtering Operator

Filtering operators are used for filtering collections based on specified conditions. There are two filtering operators -- Where and OfType<>.

Where does the same thing as the where clause in SQL server. Where filters collections based on specified conditions, as in the below example

I have used the where clause with department Id so it will filter collections based on deparment and return values which have the same deparmentid =100.

OfType filters collections based on specified types. Here in the below example I have used OfType<string> so it will give me all string type values from a collection. The output of the below example is FirstString and Secondstring because I have only two string values in collection.
  1. Console.WriteLine("====================== Where Operator =================");  
  2.            var resultWhere = from emp in employeeList  
  3.                              where emp.DepartmentId == 1001  
  4.                              select emp.Name;  
  5.   
  6.            foreach (var item in resultWhere)  
  7.            {  
  8.                Console.WriteLine(item);  
  9.            }  
  10.   
  11.            Console.WriteLine("==================== OfType Operator ==================");  
  12.            ArrayList arryList = new ArrayList();  
  13.            arryList.Add(new int[1]);  
  14.            arryList.Add(new StringBuilder());  
  15.            arryList.Add(new string[1]);  
  16.            arryList.Add("FisrtString");  
  17.            arryList.Add("SecondString");  
  18.   
  19.            var ofTypeResult = arryList.OfType<string>();  
  20.            foreach (var item in ofTypeResult)  
  21.            {  
  22.                Console.WriteLine(item);  
  23.            }  

LINQ

 

Grouping Operator

In SQL, group by clause works the same way grouping operator does in LINQ. Groupby Implemets Igrouping<TKey,TSource> interface. TKey is key values and TSource is a list of values which match with the given grouping key. 

GroupBy returns the group of elements based on a given group key value. Here in the below example you can see the list of employees belongs to the same department so it will return the employee list based on department.

LookUp aslo does the same thing as GroupBy;  the difference is that Lookup is an immediate execution. One more things to note about Lookup is that it is valid only in method syntax ,not in query sntax.

  1. Console.WriteLine("======================= GroupBy Operator ===============");  
  2.   
  3.            var resultGroupBy = from dept in deparmentList  
  4.                                join emp in employeeList  
  5.                                on dept.DepartmentId equals emp.DepartmentId  
  6.                                into employeeGroup  
  7.                                select new  
  8.                                {  
  9.                                    Employees = employeeGroup,  
  10.                                    Department = dept.DepartmentName  
  11.                                };  
  12.                                  
  13.   
  14.            foreach (var deptGroup in resultGroupBy)  
  15.            {  
  16.                Console.WriteLine(deptGroup.Department);  
  17.   
  18.                foreach (var item in deptGroup.Employees)  
  19.                {  
  20.                    Console.WriteLine("-" + item.Name);  
  21.                }  
  22.                  
  23.            }  
  24.   
  25.            Console.WriteLine("====================== ToLookup Operator =================");  
  26.   
  27.            var resultToLookUp = employeeList.ToLookup(emp => emp.DepartmentId);  
  28.   
  29.            foreach (var group in resultToLookUp)  
  30.            {  
  31.                Console.WriteLine(group.Key);  
  32.                foreach (var item in group)  
  33.                {  
  34.                    Console.WriteLine("Employee Name : " + item.Name);  
  35.                }  
  36.            }  
LINQ

Sorting Operator 

Sorting operators are used for arranging elements in collections, either by ascending or descending order. LINQ supports the below operators to arrage element either by ascending or descending order in collection.

OerderBy sorts the collection in ascending or descending order based on a given column/field. Default sorting is ascending order because in LINQ, the ascending keyword is optional; it will sort collection in ascending order by default.

One thing to note about the below three sorting operators is that they are valid only in method syntax not in query syntax.

OrderByDescending sorts the collection in descending order based on specified fields.
 
ThenBy operator is sthe econd level of sorting operator which will sort collections in ascending order based on specified fields.

ThenByDescending operator is also the second level of sorting operator, which will sort collections in descending order based on specified fields.

Reverse operator sorts collection in reverse order
  1.            Console.WriteLine("====================== OrderBy Operator ================");    
  2.     
  3.            var resultOrderBy = from emp in employeeList    
  4.                                orderby emp.Name    
  5.                                select new { emp.Name };    
  6.            foreach (var item in resultOrderBy)    
  7.            {    
  8.                Console.WriteLine(item.Name);    
  9.            }    
  10.     
  11.            Console.WriteLine("====================== OrderByDescending Operator =================");    
  12.     
  13.            var resultOrderByDescending = employeeList.OrderByDescending(emp => emp.Name);    
  14.            foreach (var item in resultOrderByDescending)    
  15.            {    
  16.                Console.WriteLine(item.Name);    
  17.            }    
  18.     
  19.            Console.WriteLine("====================== ThenBy Operator =================");    
  20.     
  21.            var resultThenBy = employeeList.OrderBy(emp => emp.DepartmentId).ThenBy(emp => emp.Name);    
  22.            foreach (var item in resultThenBy)    
  23.            {    
  24.                Console.WriteLine(item.Name);    
  25.            }    
  26.     
  27.            Console.WriteLine("====================== ThenByDescending Operator =================");    
  28.     
  29.            var resultThenByDescending = employeeList.OrderBy(emp => emp.DepartmentId).ThenByDescending(emp => emp.Name);    
  30.            foreach (var item in resultThenByDescending)    
  31.            {    
  32.                Console.WriteLine(item.Name);    
  33.            }    
  34.                
  35.            Console.ReadLine();   
LINQ
 
Conclusion

LINQ provides many extension methods for filtering, grouping, sorting and many more which will make developers' lives easy. We can use the above operators with lamda expression and it make s it simpler to retrieve data, filter data, and arrange data in a collection.

To learn more about C# 7.0 features:

Thank you for reading.

Happy learning.