Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Custom LINQ extension methods in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Custom LINQ extension methods
Define static class
↓
Write extension method
↓
Use 'this' keyword on first parameter
↓
Call method on IEnumerable object
↓
Method executes on each element
↓
Return new IEnumerable or result
↓
Use result in code
You create a static class with a static method that extends IEnumerable<T> using 'this'. Then you call it like a normal LINQ method on collections.
Execution Sample
C Sharp (C#)
public static class MyLinqExtensions {
  public static IEnumerable<int> EvenNumbers(this IEnumerable<int> source) {
    foreach(var num in source) if(num % 2 == 0) yield return num;
  }
}

var nums = new List<int>{1,2,3,4};
var evens = nums.EvenNumbers();
This code defines an extension method EvenNumbers that filters even integers from a list.
Execution Table
StepActionInputConditionOutput/Result
1Call EvenNumbers on nums[1,2,3,4]N/AReturns IEnumerable<int> (deferred)
2Start foreach in EvenNumbers11 % 2 == 0? FalseNo yield
3Next foreach22 % 2 == 0? Trueyield return 2
4Next foreach33 % 2 == 0? FalseNo yield
5Next foreach44 % 2 == 0? Trueyield return 4
6End foreachN/ANo more elementsIteration ends
7Use evens in codeIEnumerable<int>N/ASequence: 2, 4
💡 All elements processed; method yields only even numbers.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6Final
numN/A1234N/AN/A
evens (deferred)N/AIEnumerable<int>IEnumerable<int>IEnumerable<int>IEnumerable<int>IEnumerable<int>[2,4]
Key Moments - 3 Insights
Why does EvenNumbers return IEnumerable<int> but not a list immediately?
Because the method uses 'yield return', it creates a deferred sequence. The actual filtering happens when you iterate over the result, as shown in steps 2-6.
How does the 'this' keyword make EvenNumbers an extension method?
The 'this' keyword before the first parameter tells C# this method extends IEnumerable<int>. So you can call it like nums.EvenNumbers(), as in step 1.
What happens if the input list is empty?
The foreach loop in EvenNumbers won't run, so no elements are yielded. The output will be an empty IEnumerable, similar to step 6 but immediately.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'num' at Step 4?
A2
B4
C3
D1
💡 Hint
Check the 'num' variable column in variable_tracker after Step 4.
At which step does the method yield the first even number?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at the 'Output/Result' column in execution_table for when 'yield return' happens.
If the input list was empty, how would the execution table change?
AMethod would yield all numbers anyway
BSteps 2-5 would be skipped; method ends immediately
CMethod would throw an error
DMethod would yield one element
💡 Hint
Refer to key_moments about empty input behavior.
Concept Snapshot
Custom LINQ extension methods:
- Define a static class
- Write static method with 'this' on first param
- Method extends IEnumerable<T>
- Use 'yield return' for deferred execution
- Call like normal LINQ method on collections
Full Transcript
This visual trace shows how to create and use a custom LINQ extension method in C#. We define a static class with a static method called EvenNumbers that extends IEnumerable<int> using the 'this' keyword. The method filters even numbers using a foreach loop and 'yield return' to produce a deferred sequence. When called on a list of numbers, the method does not immediately return a list but an IEnumerable that yields even numbers as you iterate. The execution table walks through each step of the foreach loop, showing which numbers are checked and which are yielded. The variable tracker shows how the 'num' variable changes each iteration and how the 'evens' variable holds the deferred sequence until iteration. Key moments clarify why 'yield return' causes deferred execution and how the 'this' keyword enables extension method syntax. The quiz tests understanding of variable values at steps, when yields happen, and behavior with empty input. This helps beginners see exactly how custom LINQ extension methods run step-by-step.

Practice

(1/5)
1. What is a key requirement for creating a custom LINQ extension method in C#?
easy
A. It must be a static method inside a static class with this on the first parameter.
B. It must be an instance method inside any class.
C. It must return void and take no parameters.
D. It must be declared inside the Main method.

Solution

  1. Step 1: Understand extension method structure

    Extension methods must be static methods inside static classes.
  2. Step 2: Identify the special parameter usage

    The first parameter must have the this keyword to specify the type it extends.
  3. Final Answer:

    It must be a static method inside a static class with this on the first parameter. -> Option A
  4. Quick Check:

    Extension method = static + static class + this param [OK]
Hint: Remember: static method + static class + this param [OK]
Common Mistakes:
  • Making the method non-static
  • Forgetting the static class container
  • Omitting the 'this' keyword on the first parameter
2. Which of the following is the correct syntax to declare a custom LINQ extension method named IsEven for IEnumerable<int>?
easy
A. public static bool IsEven(this IEnumerable<int> source) { ... }
B. public bool IsEven(IEnumerable<int> source) { ... }
C. static bool IsEven(IEnumerable<int> source) { ... }
D. public static bool IsEven(IEnumerable<int> source) { ... }

Solution

  1. Step 1: Check method modifiers and parameters

    The method must be public static and have this before the first parameter to be an extension method.
  2. Step 2: Verify the parameter type and method signature

    public static bool IsEven(this IEnumerable<int> source) { ... } correctly uses this IEnumerable<int> source and is static and public.
  3. Final Answer:

    public static bool IsEven(this IEnumerable<int> source) { ... } -> Option A
  4. Quick Check:

    Extension method syntax = public static + this param [OK]
Hint: Look for 'public static' and 'this' on first parameter [OK]
Common Mistakes:
  • Missing 'this' keyword on the first parameter
  • Not making the method static
  • Incorrect access modifier
3. Given this custom LINQ extension method, what will be the output?
public static IEnumerable<int> GetPositive(this IEnumerable<int> source) {
    foreach (var num in source) {
        if (num > 0) yield return num;
    }
}

var numbers = new List<int> { -1, 0, 3, 5, -2 };
var result = numbers.GetPositive().ToList();
Console.WriteLine(string.Join(",", result));
medium
A. -1,0,3,5,-2
B. 0,3,5
C. 3,5,-2
D. 3,5

Solution

  1. Step 1: Understand the extension method logic

    The method yields only numbers greater than zero from the source list.
  2. Step 2: Apply the method to the list

    From the list [-1, 0, 3, 5, -2], only 3 and 5 are greater than zero and yielded.
  3. Final Answer:

    3,5 -> Option D
  4. Quick Check:

    Filter positive numbers = 3,5 [OK]
Hint: Focus on the 'if (num > 0)' filter condition [OK]
Common Mistakes:
  • Including zero as positive
  • Returning all numbers without filtering
  • Confusing yield return with return
4. Identify the error in this custom LINQ extension method:
public static IEnumerable<int> FilterEven(IEnumerable<int> source) {
    foreach (var num in source) {
        if (num % 2 == 0) yield return num;
    }
}
medium
A. Cannot use 'yield return' inside a foreach loop.
B. Method should return void instead of IEnumerable<int>.
C. Missing 'this' keyword on the first parameter to make it an extension method.
D. The modulo operator '%' is not valid in C#.

Solution

  1. Step 1: Check extension method signature

    The method lacks the this keyword on the first parameter, so it is not an extension method.
  2. Step 2: Verify other syntax elements

    Using yield return inside a foreach is valid, and '%' is a valid operator in C#.
  3. Final Answer:

    Missing 'this' keyword on the first parameter to make it an extension method. -> Option C
  4. Quick Check:

    Extension method requires 'this' on first parameter [OK]
Hint: Extension methods always need 'this' on first parameter [OK]
Common Mistakes:
  • Forgetting 'this' keyword
  • Thinking 'yield return' is invalid in loops
  • Misunderstanding the modulo operator
5. You want to create a custom LINQ extension method ToDictionaryByLength that converts an IEnumerable<string> into a Dictionary<int, List<string>>, grouping strings by their length. Which implementation correctly achieves this?
hard
A. public static Dictionary ToDictionaryByLength(IEnumerable<string> source) { return source.ToDictionary(s => s.Length, s => new List<string> { s }); }
B. public static Dictionary ToDictionaryByLength(this IEnumerable<string> source) { return source.GroupBy(s => s.Length) .ToDictionary(g => g.Key, g => g.ToList()); }
C. public static Dictionary ToDictionaryByLength(this IEnumerable<string> source) { var dict = new Dictionary(); foreach (var s in source) { dict[s.Length] = new List<string> { s }; } return dict; }
D. public static Dictionary ToDictionaryByLength(this IEnumerable<string> source) { return source.ToDictionary(s => s.Length, s => s); }

Solution

  1. Step 1: Understand grouping by length

    We need to group strings by their length, so GroupBy with key s.Length is correct.
  2. Step 2: Convert groups to dictionary

    Use ToDictionary with group key and list of strings as value.
  3. Step 3: Check other options

    public static Dictionary ToDictionaryByLength(IEnumerable<string> source) { return source.ToDictionary(s => s.Length, s => new List<string> { s }); } does not group; it tries to create dictionary with duplicate keys causing error. public static Dictionary ToDictionaryByLength(this IEnumerable<string> source) { var dict = new Dictionary(); foreach (var s in source) { dict[s.Length] = new List<string> { s }; } return dict; } overwrites values instead of adding to list. public static Dictionary ToDictionaryByLength(this IEnumerable<string> source) { return source.ToDictionary(s => s.Length, s => s); } tries to map to string instead of list.
  4. Final Answer:

    public static Dictionary<int, List<string>> ToDictionaryByLength(this IEnumerable<string> source) { return source.GroupBy(s => s.Length) .ToDictionary(g => g.Key, g => g.ToList()); } -> Option B
  5. Quick Check:

    GroupBy + ToDictionary with list = correct grouping [OK]
Hint: Use GroupBy then ToDictionary with list conversion [OK]
Common Mistakes:
  • Not grouping before ToDictionary
  • Overwriting dictionary entries instead of adding to list
  • Returning wrong value types in dictionary
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard