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

Custom LINQ extension methods in C Sharp (C#) - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define an extension method that returns the first element of a sequence.

C Sharp (C#)
public static T [1]<T>(this IEnumerable<T> source) {
    foreach (var item in source) {
        return item;
    }
    throw new InvalidOperationException("Sequence contains no elements");
}
Drag options to blanks, or click blank then click option'
AFirst
BSelect
CWhere
DOrderBy
Attempts:
3 left
💡 Hint
Common Mistakes
Using a LINQ method name that does not return a single element.
Forgetting to make the method an extension method with 'this' keyword.
2fill in blank
medium

Complete the code to define an extension method that filters elements based on a predicate.

C Sharp (C#)
public static IEnumerable<T> [1]<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
    foreach (var item in source) {
        if (predicate(item)) {
            yield return item;
        }
    }
}
Drag options to blanks, or click blank then click option'
ASelect
BOrderBy
CWhere
DGroupBy
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Select' which transforms elements instead of filtering.
Not using 'yield return' to return filtered elements lazily.
3fill in blank
hard

Fix the error in the extension method that projects each element to a new form.

C Sharp (C#)
public static IEnumerable<TResult> Select<T, TResult>(this IEnumerable<T> source, Func<T, TResult> selector) {
    foreach (var item in source) {
        yield return [1];
    }
}
Drag options to blanks, or click blank then click option'
Aitem
Bselector(item)
Csource
Dselector
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the item itself instead of applying the selector.
Returning the selector delegate instead of calling it.
4fill in blank
hard

Fill both blanks to create an extension method that counts elements matching a condition.

C Sharp (C#)
public static int Count<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
    int count = 0;
    foreach (var item in source) {
        if (predicate(item) [1] true) {
            count [2] 1;
        }
    }
    return count;
}
Drag options to blanks, or click blank then click option'
A=>
B==
C+=
D-=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=>' which is not a comparison operator.
Using '-=' which decreases the count incorrectly.
5fill in blank
hard

Fill both blanks to create an extension method that returns a dictionary with keys and values selected from the source.

C Sharp (C#)
public static Dictionary<TKey, TValue> ToDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> valueSelector) {
    var dict = new Dictionary<TKey, TValue>();
    foreach (var item in source) {
        dict.[1](keySelector(item), [2]);
    }
    return dict;
}
Drag options to blanks, or click blank then click option'
AAdd
BvalueSelector(item)
Citem
DRemove
Attempts:
3 left
💡 Hint
Common Mistakes
Using Remove instead of Add.
Passing the item directly instead of the selected value.

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