How To Use Extensions For LINQ - C#

In this tutorial, we will learn how to use extension methods with LINQ in C# to simplify the coding.

How To Use Extensions For LINQ
 

Introduction

Extension Methods are a new feature in C# 3.0, and they're simply user-made pre-defined functions. An Extension Method enables us to add methods to existing types without creating a new derived type, recompiling, or modifying the original types.

Extension Methods

  • It enables us to add methods to existing types without creating a new derived type.
  • It is a static method.
  • It is defined in a static class.
  • It uses “this” keyword to apply the extension to the particular type.
  • We don’t want to compile the application. Visual Studio IntelliSense will find the extension method immediately.

Coding Part

  1. I have created a Console application by selecting File->New Project->Console Application.
  2. Then, created a Model class “Employee.cs” with member variables like below.
    1. public class Employee  
    2. {  
    3.     public string Name { getset; }  
    4.     public string MobileNo { getset; }  
    5.     public string Salary { getset; }  
    6.   
    7.     public string String()  
    8.     {  
    9.         return string.Format("Name:{0} MobileNo:{1} Salary:{2}", Name, MobileNo, Salary);  
    10.     }  
    11. }  
  1. Then, I added the values to employee list as below.
    1. static void AddEmployees()  
    2. {  
    3.     employees.Add(new Employee() { Name = "Mushtaq", MobileNo = "9876543210", Salary = "20K" });  
    4.     employees.Add(new Employee() { Name = "Mohammed Mushtaq", MobileNo = "9876543211", Salary = "30K" });  
    5.     employees.Add(new Employee() { Name = "Mushtaq Ahmed", MobileNo = "9876543212", Salary = "20K" });  
    6.     employees.Add(new Employee() { Name = "Raj", MobileNo = "9876543213", Salary = "25K" });  
    7. }  
  1. Now, we will get results from a list using Linq for “FirstOrDefault”, “LastOrDefault” or “IndexOf”.
    1. Console.WriteLine(employees.Where(x => x.Name.Contains("Mushtaq")).FirstOrDefault().String());  
    2. Console.WriteLine(employees.Where(x => x.Name.Contains("Mushtaq")).LastOrDefault().String());  
    3. Console.WriteLine(employees.IndexOf(employees.Where(x => x.Name.Contains("Mushtaq")).FirstOrDefault()));  
    Result

    How To Use Extensions For LINQ
  1. Now, I have created a static class named as “LinqExtension.cs” and created extension methods for selecting “FirstOrDefault”, “LastOrDefault” and getting the index of the object from the list using LINQ.
    1. public static class LinqExtension  
    2. {  
    3.     public static T WhereFirstOrDefault<T>(this List<T> list, Func<T, bool> predicate)  
    4.     {  
    5.         return list.Where(predicate).FirstOrDefault();  
    6.     }  
    7.     public static T WhereLastOrDefault<T>(this List<T> list, Func<T, bool> predicate)  
    8.     {  
    9.         return list.Where(predicate).LastOrDefault();  
    10.     }  
    11.     public static int IndexOf<T>(this List<T> list, Func<T, bool> predicate)  
    12.     {  
    13.         return list.IndexOf(list.WhereFirstOrDefault(predicate));  
    14.     }  
    15.  
  1. The extension methods can be implemented as below.
    1. Console.WriteLine(employees.WhereFirstOrDefault(x => x.Name.Contains("Mushtaq")).String());  
    2. Console.WriteLine(employees.WhereLastOrDefault(x => x.Name.Contains("Mushtaq")).String());  
    3. Console.WriteLine(employees.IndexOf(x => x.Name.Contains("Mushtaq")));  

Result

How To Use Extensions For LINQ

 

The extension will return the same result. But the line of code will be less, comparatively.

Full Code

Full code implementations of extension methods.

  1. namespace ExtensionsWithLinq  
  2. {  
  3.     class Program  
  4.     {  
  5.         static List<Employee> employees = new List<Employee>();  
  6.         static void Main(string[] args)  
  7.         {  
  8.             AddEmployees();  
  9.   
  10.             Console.WriteLine("...Extension with Linq...");  
  11.             Console.WriteLine();  
  12.             Console.WriteLine();  
  13.             Console.WriteLine("Linq to get details of Mushtaq with Linq-FirstOrDefault");  
  14.             Console.WriteLine();  
  15.             Console.WriteLine(employees.Where(x => x.Name.Contains("Mushtaq")).FirstOrDefault().String());  
  16.   
  17.             Console.WriteLine();  
  18.             Console.WriteLine();  
  19.             Console.WriteLine("Linq to get details of Mushtaq with Linq-LastOrDefault");  
  20.             Console.WriteLine();  
  21.             Console.WriteLine(employees.Where(x => x.Name.Contains("Mushtaq")).LastOrDefault().String());  
  22.   
  23.             Console.WriteLine();  
  24.             Console.WriteLine();  
  25.             Console.WriteLine("Linq to get index of Mushtaq with Linq-IndexOf");  
  26.             Console.WriteLine();  
  27.             Console.WriteLine(employees.IndexOf(employees.Where(x => x.Name.Contains("Mushtaq")).FirstOrDefault()));  
  28.   
  29.             Console.WriteLine();  
  30.             Console.WriteLine();  
  31.             Console.WriteLine("Linq to get details of Mushtaq with Linq-FirstOrDefault Extension");  
  32.             Console.WriteLine();  
  33.             Console.WriteLine(employees.WhereFirstOrDefault(x => x.Name.Contains("Mushtaq")).String());  
  34.   
  35.             Console.WriteLine();  
  36.             Console.WriteLine();  
  37.             Console.WriteLine("Linq to get details of Mushtaq with Linq-LastOrDefault Extension");  
  38.             Console.WriteLine();  
  39.             Console.WriteLine(employees.WhereLastOrDefault(x => x.Name.Contains("Mushtaq")).String());  
  40.   
  41.             Console.WriteLine();  
  42.             Console.WriteLine();  
  43.             Console.WriteLine("Linq to get index of Mushtaq with Linq-IndexOf Extension");  
  44.             Console.WriteLine();  
  45.             Console.WriteLine(employees.IndexOf(x => x.Name.Contains("Mushtaq")));  
  46.   
  47.             Console.ReadLine();  
  48.         }  
  49.   
  50.         static void AddEmployees()  
  51.         {  
  52.             employees.Add(new Employee() { Name = "Mushtaq", MobileNo = "9876543210", Salary = "20K" });  
  53.             employees.Add(new Employee() { Name = "Mohammed Mushtaq", MobileNo = "9876543211", Salary = "30K" });  
  54.             employees.Add(new Employee() { Name = "Mushtaq Ahmed", MobileNo = "9876543212", Salary = "20K" });  
  55.             employees.Add(new Employee() { Name = "Raj", MobileNo = "9876543213", Salary = "25K" });  
  56.         }  
  57.     }  
  58. }  

Reference

Linq  https://docs.microsoft.com/en-us/dotnet/csharp/linq/ 
Extensions  https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods 

Download Code

You can download the code from GitHub. If you have doubts, feel free to post a comment. If you like this article and it is useful to you, do like, share the article & star the repository on GitHub.