Custom LINQ extension methods let you add your own easy-to-use commands to work with lists and collections. This helps you write cleaner and simpler code.
0
0
Custom LINQ extension methods in C Sharp (C#)
Introduction
You want to reuse a special way to filter or change a list in many places.
You need a new operation on collections that LINQ does not provide by default.
You want your code to read like natural language when working with data.
You want to keep your main code clean by moving complex logic into small methods.
You want to chain multiple operations on collections smoothly.
Syntax
C Sharp (C#)
public static class MyExtensions { public static IEnumerable<T> MyMethod<T>(this IEnumerable<T> source) { // Your code here yield return default(T); } }
The method must be inside a static class.
The first parameter uses this keyword to mark it as an extension method.
Examples
This method returns only even numbers from a list of integers.
C Sharp (C#)
public static class Extensions { public static IEnumerable<int> EvenNumbers(this IEnumerable<int> numbers) { foreach (var n in numbers) if (n % 2 == 0) yield return n; } }
This method returns every other item from a collection.
C Sharp (C#)
public static class Extensions { public static IEnumerable<T> TakeEveryOther<T>(this IEnumerable<T> source) { bool take = true; foreach (var item in source) { if (take) yield return item; take = !take; } } }
Sample Program
This program defines a custom extension method EvenNumbers that filters even numbers from a list. It then prints each even number.
C Sharp (C#)
using System; using System.Collections.Generic; using System.Linq; public static class Extensions { public static IEnumerable<int> EvenNumbers(this IEnumerable<int> numbers) { foreach (var n in numbers) if (n % 2 == 0) yield return n; } } class Program { static void Main() { var nums = new List<int> {1, 2, 3, 4, 5, 6}; var evens = nums.EvenNumbers(); foreach (var e in evens) Console.WriteLine(e); } }
OutputSuccess
Important Notes
Extension methods help keep your code clean and readable.
Use yield return to return items one by one without creating a new list.
Remember to include using for the namespace where your extension methods live.
Summary
Custom LINQ extension methods add new commands to collections.
They must be static methods inside static classes with this on the first parameter.
They make your code easier to read and reuse.