Showing posts with label C#. Show all posts

Introduction: In this tutorial, we will learn how to use extension methods with Linq in C# to simplify the coding. Extension Methods are...

How to use Extensions for Linq – C# How to use Extensions for Linq – C#

A blog about android developement

C#


Introduction:

In this tutorial, we will learn how to use extension methods with Linq in C# to simplify the coding. Extension Methods are a new feature in C# 3.0 and is nothing but a user made pre-defined functions. An Extension Method enables us to add methods to existing types without creating a new derived type, recompiling, or modify the original types.

Extension Methods:

  1. It enable us to add methods to existing types without creating a new derived type.
  2. It is a static method.
  3. It is defined in a static class.
  4. It uses “this” keyword to apply the extension to the particular type.
  5. We don’t want to compile the application. Visual Studio intelli-sense 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.
    public class Employee
    {
     public string Name { get; set; }
     public string MobileNo { get; set; }
     public string Salary { get; set; }
    
     public string String()
     {
      return string.Format("Name:{0} MobileNo:{1} Salary:{2}", Name, MobileNo, Salary);
     }
    }
  3. Then added values to employee list as like below
    static void AddEmployees()
    {
     employees.Add(new Employee() { Name = "Mushtaq", MobileNo = "9876543210", Salary = "20K" });
     employees.Add(new Employee() { Name = "Mohammed Mushtaq", MobileNo = "9876543211", Salary = "30K" });
     employees.Add(new Employee() { Name = "Mushtaq Ahmed", MobileNo = "9876543212", Salary = "20K" });
     employees.Add(new Employee() { Name = "Raj", MobileNo = "9876543213", Salary = "25K" });
    }
  4. Now we will get results from list using Linq for “FirstOrDefault”, “LastOrDefault” or “IndexOf”.
    Console.WriteLine(employees.Where(x => x.Name.Contains("Mushtaq")).FirstOrDefault().String());
    Console.WriteLine(employees.Where(x => x.Name.Contains("Mushtaq")).LastOrDefault().String());
    Console.WriteLine(employees.IndexOf(employees.Where(x => x.Name.Contains("Mushtaq")).FirstOrDefault()));
    Result:
  5. Now I have created a static class named as “LinqExtension.cs” and created extension methods for selecting “FirstOrDefault”, “LastOrDefault” and getting index of the object from list using Linq.
    public static class LinqExtension
    {
     public static T WhereFirstOrDefault(this List list, Func predicate)
     {
      return list.Where(predicate).FirstOrDefault();
     }
     public static T WhereLastOrDefault(this List list, Func predicate)
     {
      return list.Where(predicate).LastOrDefault();
     }
     public static int IndexOf(this List list, Func predicate)
     {
      return list.IndexOf(list.WhereFirstOrDefault(predicate));
     }
    }
  6. The extension methods can be implemented as like the below
    Console.WriteLine(employees.WhereFirstOrDefault(x => x.Name.Contains("Mushtaq")).String());
    Console.WriteLine(employees.WhereLastOrDefault(x => x.Name.Contains("Mushtaq")).String());
    Console.WriteLine(employees.IndexOf(x => x.Name.Contains("Mushtaq")));
    Result:
  7. The extension will return the same result. But the line of code will be less comparatively.

Full Code:

Full code implementations of extension methods.

namespace ExtensionsWithLinq
{
    class Program
    {
        static List employees = new List();
        static void Main(string[] args)
        {
            AddEmployees();

            Console.WriteLine("...Extension with Linq...");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Linq to get details of Mushtaq with Linq-FirstOrDefault");
            Console.WriteLine();
            Console.WriteLine(employees.Where(x => x.Name.Contains("Mushtaq")).FirstOrDefault().String());

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Linq to get details of Mushtaq with Linq-LastOrDefault");
            Console.WriteLine();
            Console.WriteLine(employees.Where(x => x.Name.Contains("Mushtaq")).LastOrDefault().String());

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Linq to get index of Mushtaq with Linq-IndexOf");
            Console.WriteLine();
            Console.WriteLine(employees.IndexOf(employees.Where(x => x.Name.Contains("Mushtaq")).FirstOrDefault()));

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Linq to get details of Mushtaq with Linq-FirstOrDefault Extension");
            Console.WriteLine();
            Console.WriteLine(employees.WhereFirstOrDefault(x => x.Name.Contains("Mushtaq")).String());

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Linq to get details of Mushtaq with Linq-LastOrDefault Extension");
            Console.WriteLine();
            Console.WriteLine(employees.WhereLastOrDefault(x => x.Name.Contains("Mushtaq")).String());

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Linq to get index of Mushtaq with Linq-IndexOf Extension");
            Console.WriteLine();
            Console.WriteLine(employees.IndexOf(x => x.Name.Contains("Mushtaq")));

            Console.ReadLine();
        }

        static void AddEmployees()
        {
            employees.Add(new Employee() { Name = "Mushtaq", MobileNo = "9876543210", Salary = "20K" });
            employees.Add(new Employee() { Name = "Mohammed Mushtaq", MobileNo = "9876543211", Salary = "30K" });
            employees.Add(new Employee() { Name = "Mushtaq Ahmed", MobileNo = "9876543212", Salary = "20K" });
            employees.Add(new Employee() { Name = "Raj", MobileNo = "9876543213", Salary = "25K" });
        }
    }
}

Reference:

Linqhttps://docs.microsoft.com/en-us/dotnet/csharp/linq/
Extensionshttps://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 doubt, feel free to post comment. If you like this article and is useful to you, do like, share the article & star the repository on GitHub.