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:
- It enable 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 intelli-sense will find the extension method immediately.
Coding Part:
- I have created a Console application by selecting File->New Project->Console Application.
- 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); } } - 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" }); } - Now we will get results from list using Linq for “FirstOrDefault”, “LastOrDefault” or “IndexOf”.
Result: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())); - 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)); } } - The extension methods can be implemented as like the below
Result: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"))); - 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:
| 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 |



Great article Lot's of information to Read...Great Man Keep Posting and update to People..Thanks app cloner premium
ReplyDeleteHey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. blackmart apk free * blackmart alpha pro * blackmart apk latest update
ReplyDeleteC027E5A054
ReplyDeletetakipçi satın al
Tiktok Takipçi Arttırma
İG Takipçi
Yabancı Numara Al
MMORPG Oyunlar
17E8E893EA
ReplyDeleteBeğeni Satın Al
EFT ile Takipçi
Takipçi Fiyatları
ReplyDeleteİnternet üzerinden eğlenceli vakit geçirmek isteyenler için çeşitli içerikler mevcut. Özellikle canlı yayınlar ve interaktif gösteriler büyük ilgi görüyor. Bu tür etkinlikleri deneyimlemek isteyenler, görüntülü show gibi platformları tercih edebilirler. Bu sayede hem eğlenceyi doruklarda yaşayabilir hem de farklı deneyimler kazanabilirler.