Goal: ForEach extension masking Select.
Reason: Select allows for method chaining while foreach does not; ForEach is more readable than Select.
The problem I'm running into is that I'm getting this error.
The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly. (CS0411)
public static void ForEach<T>(this IEnumerable<T> elements, Action<T, int> action)
{
elements.Select((elem, i) => action(elem, i));
}
I've tried doing elements.Select((T elem, int i) => action(elem, i));
but that produces the same error.
I've also attempted using Func instead of Action but there doesn't seem to be any way to use void for the return (which is what Action is for anyways). If I define the method to take a Func instead of Action then when I try to call it using Action I get the same error.
public static IEnumerable<TOut> ForEach<TIn, TOut>(this IEnumerable<TIn> elements,
Func<TIn, int, TOut> function)
{
return elements.Select((elem, i) => function(elem, i))
.ToList();
}
I don't understand which arguments cannot be inferred. There are ways I could get around this (using a for loop or foreach loop and track the index), but I would still like to figure out why this won't work.
Edit: I also just realized my other ForEach for Action (no index) also gets this error when I switch from a foreach loop to calling Select.
public static void ForEach<T>(this IEnumerable<T> elements, Action<T> action)
{
elements.ToList().Select((T elem) => action(elem));
/*foreach (var elem in elements)
action(elem);*/
}
Select
at all? If you want to writeForEach
, just use aforeach
statement... – Jon SkeetSelect
is meant to take a projection, to go from one type to another? What do you expect the compiler to infer here, given thataction(elem)
andaction(elem, i)
don't return anything? – Jon Skeet