I often come across code like the following:
if ( items != null)
{
foreach(T item in items)
{
//...
}
}
Basically, the
You can encapsulate the null check in an extension method and use a lambda:
public static class EnumerableExtensions {
public static void ForEach(this IEnumerable self, Action action) {
if (self != null) {
foreach (var element in self) {
action(element);
}
}
}
}
The code becomes:
items.ForEach(item => {
...
});
If can be even more concise if you want to just call a method that takes an item and returns void
:
items.ForEach(MethodThatTakesAnItem);