Write extension methods:
static class IEnumerableForEachExtensions {
public static void ForEachMatch<T>(this IEnumerable<T> items,
Predicate<T> predicate,
Action<T> action
) {
items.Where(x => predicate(x)).ForEach(action);
}
public static void ForEach<T>(this IEnumerable<T> items, Action<T> action) {
foreach(T item in items) {
action(item);
}
}
}
Usage:
// list is List<string>
list.ForEachMatch(s => s.StartsWith("a"), s => Console.WriteLine(s));
Note this is fully general as it will eat any IEnumerable<T>
. Note that there are some that would consider this an abuse of LINQ because of the explicit side effects.