Complete the code to define an extension method that returns the first element of a sequence.
public static T [1]<T>(this IEnumerable<T> source) { foreach (var item in source) { return item; } throw new InvalidOperationException("Sequence contains no elements"); }
The method name First is used to get the first element in a sequence.
Complete the code to define an extension method that filters elements based on a predicate.
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; } } }
The method Where filters elements based on a condition (predicate).
Fix the error in the extension method that projects each element to a new form.
public static IEnumerable<TResult> Select<T, TResult>(this IEnumerable<T> source, Func<T, TResult> selector) {
foreach (var item in source) {
yield return [1];
}
}The Select method applies the selector function to each item and returns the result.
Fill both blanks to create an extension method that counts elements matching a condition.
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;
}The condition uses == to check if predicate returns true, and += increments the count.
Fill both blanks to create an extension method that returns a dictionary with keys and values selected from the source.
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;
}The method Add inserts a key and value into the dictionary. The value is obtained by calling valueSelector(item).