Complete the code to define an extension method for IEnumerable<int>.
public static class Extensions { public static int Sum(this IEnumerable<int> [1]) { int total = 0; foreach (var num in source) { total += num; } return total; } }
this keyword before the parameter.The parameter name for the extension method must be a valid identifier. Here, source is commonly used to represent the input collection.
Complete the code to call the extension method on a list.
var numbers = new List<int> {1, 2, 3};
int total = numbers.[1]();Add or Sort.The Sum method is an extension method that calculates the total of all elements in the list.
Fix the error in the extension method declaration.
public static int CountItems([1]) { int count = 0; foreach (var item in source) { count++; } return count; }
this keyword.this after the type or parameter name incorrectly.Extension methods must have the this keyword before the first parameter's type to indicate the method extends that type.
Fill both blanks to create an extension method that filters even numbers.
public static IEnumerable<int> [1](this IEnumerable<int> source) { foreach (var num in source) { if (num [2] 2 == 0) { yield return num; } } }
Sum or Add.+ instead of modulus.The method name WhereEven describes filtering even numbers. The modulus operator % checks divisibility.
Fill all three blanks to create an extension method that converts strings to uppercase and filters by length.
public static IEnumerable<string> [1](this IEnumerable<string> source, int minLength) { foreach (var str in source) { var upper = str.[2](); if (upper.Length [3] minLength) { yield return upper; } } }
ToLower instead of ToUpper.<.The method name FilterAndUpper describes the operation. ToUpper() converts strings to uppercase. The operator >= filters strings with length greater or equal to minLength.