📖 Scenario: You work with lists of numbers and want to create your own special filters and operations, just like LINQ does. This helps you reuse code and write cleaner programs.
🎯 Goal: Build a custom LINQ extension method called IsEven that filters only even numbers from a list of integers.
📋 What You'll Learn
Create a list of integers called numbers with the values 1, 2, 3, 4, 5, 6
Create a boolean extension method called IsEven for integers
Use the IsEven method in a LINQ Where clause to filter even numbers
Print the filtered even numbers separated by spaces
💡 Why This Matters
🌍 Real World
Custom LINQ extension methods help you add your own reusable filters and operations to collections, making your code cleaner and easier to read.
💼 Career
Many software jobs require writing clean, reusable code. Knowing how to create and use extension methods is a valuable skill for working with collections and LINQ in C#.
Progress0 / 4 steps
1
Create the list of numbers
Create a list of integers called numbers with these exact values: 1, 2, 3, 4, 5, 6.
C Sharp (C#)
Hint
Use List<int> and initialize it with the values inside curly braces.
2
Create the IsEven extension method
Create a public static class called Extensions. Inside it, create a public static method called IsEven that takes this int number as a parameter and returns true if the number is even, otherwise false.
C Sharp (C#)
Hint
Extension methods must be inside a static class and have this before the first parameter.
3
Use IsEven in a LINQ Where clause
Inside Main, create a variable called evenNumbers that uses numbers.Where(n => n.IsEven()) to filter only even numbers.
C Sharp (C#)
Hint
Use Where with a lambda expression calling IsEven() on each number.
4
Print the filtered even numbers
Print the evenNumbers separated by spaces using Console.WriteLine(string.Join(" ", evenNumbers)).
C Sharp (C#)
Hint
Use Console.WriteLine with string.Join to print the numbers separated by spaces.
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
Step 1: Understand extension method structure
Extension methods must be static methods inside static classes.
Step 2: Identify the special parameter usage
The first parameter must have the this keyword to specify the type it extends.
Final Answer:
It must be a static method inside a static class with this on the first parameter. -> Option A
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
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.
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.
Final Answer:
public static bool IsEven(this IEnumerable<int> source) { ... } -> Option A
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
Step 1: Understand the extension method logic
The method yields only numbers greater than zero from the source list.
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.
Final Answer:
3,5 -> Option D
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
Step 1: Check extension method signature
The method lacks the this keyword on the first parameter, so it is not an extension method.
Step 2: Verify other syntax elements
Using yield return inside a foreach is valid, and '%' is a valid operator in C#.
Final Answer:
Missing 'this' keyword on the first parameter to make it an extension method. -> Option C
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
Step 1: Understand grouping by length
We need to group strings by their length, so GroupBy with key s.Length is correct.
Step 2: Convert groups to dictionary
Use ToDictionary with group key and list of strings as value.
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.
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
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 unknownstrongwhile earning +1 Grip toward your certificate.