Today I was visiting a client, and I just stop and watch something that really caught my attention:
foreach (item in myList) {
if (item.Length > 0) {
SaveItem(item);
}
}
// more ugly code...
Well, the code was really different (an uglier one) but you got the idea…. What I suggested to my client was a more concise solutio, create an extension method:
public static class IEnumerableExt {
public static IEnumerable<T> ForEach(this IEnumerable<T> items, Action<T> action) {
foreach(var item in items) {
action(e);
}
}
}
The second part is the easy one…
myList
.Where((item) => item.Length > 0)
.ForEach((item) => SaveItem(Item));
I don’t know you, but this way looks a lot clearer to me…
Lessson learned: If your code looks complex, please, take a time and look how to make it more clearer.