Share via


Using .Select() instead of foreach

As astute colleague noticed something funny in my recent post. Specifically, this piece of code:

postsWithCount.AsEnumerable().Select(pd => Rebuild(pd));

private void Rebuild(PostData postData)
{
Post post = postData.Post;
post.User = postData.User;
post.Comments.Attach(postData.Comments);
}

What on earth am I doing here? Maybe it will help if I write the same code in a different way:

foreach (var postData in postsWithCount)
{
Rebuild(postData);
}

private void Rebuild(PostData postData)
{
Post post = postData.Post;
post.User = postData.User;
post.Comments.Attach(postData.Comments);
}

Yup, I'm quite naughtily using Select as a ForEach. I've been experimenting with this for a while now and the outcome is clear - it makes your code confusing.

Sadly, there is a ForEach<> method on System.Array but no extension method for IEnumerable<>

Orignally posted by Josh Twist on Febuary 13th 2008 here.