I found myself wanting to use Linq to map void methods to an IEnumerable to modify all items. The existing Linq methods require a return variable when mapping, since they are based on Func
.
So I decided to try my hand at creating some extension methods myself. This is the first time I've done anything like this, so if there are any pitfalls I'm missing, please do tell.
I created two extensions, one which applies a foreach loop to all elements, calling an Action<T>
for each. The second one is basically the Zip
extension, which allows for two IEnumerable
s to be iterated together and again maps a Action<T1,T2>
to both of them.
public static void ForEachAction<T>(this IEnumerable<T> sequence, Action<T> action) {
foreach(T value in sequence) {
action(value);
}
}
public static void ForEachActionZip<Tbase, Tsecond>(this IEnumerable<Tbase> sequence, IEnumerable<Tsecond> second, Action<Tbase, Tsecond> action) {
sequence.Zip(second, (first, other) => new { first, other }).ForEachAction(x => action(x.first, x.other));
}
You can then use this like so:
someList.ForEachAction(x => x.Update());
or
someList.ForEachActionZip(secondList, (a, b) => a.Update(b));
foreach
loop instead? \$\endgroup\$foreach (var item in first.Zip(second, ...))
, where...
could produce a (value) tuple or an object of an existing or anonymous type? If used a lot, you could write aZip
extension method that doesn't require aFunc<>
argument. If it returned a value tuple, you could writeforeach (var (item1, item2) in first.Zip(second))
. \$\endgroup\$