Just a quick post to show a little extension method I created. I’m not quite sure why it’s not part of the framework already really! I'm fast beginning to see the foreach loop as a code smell, preferring a more declarative approach. In the olden-days (before-linq) it would be common to write code like this:

foreach (Person person in People)
{
  if (person.LastLogin > DateTime.Now.AddDays(-10))
    person.RecentlyActive = true;
}

Then along came linq and it became:

foreach (Person person in People.Where(p => p.LastLogin > DateTime.Now.AddDays(-10)))
{
  person.RecentlyActive = true;
}

Its getting fairly declarative now but we’re still using the loop and wasting space. You can improve this though by defining an extension method like this:

public static void Do<T>(this IEnumerable<T> items, Action<T> modifier)
{
  foreach (T item in items)
    modifier(item);
}

It just loops through each of the items in a collection and performs some action based on them. We can now change our person code to:

People.Where(p => p.LastLogin > DateTime.Now.AddDays(-10)).
    Do(p => p.RecentlyActive = true);

Nice huh?

Is there a reason this wasn't included in the framework? Is it there and I missed it? Am I doing something horrible? Will I burn eternally for this? Let me know Wink