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.
Comments
Anonymous
February 24, 2009
Just write your own Do() or Foreach() extension methods for IEnumerable<> public static IEnumerable<T> Do<T>(this IEnumerable<T> xs, Action<T> action) { foreach (var x in xs) { action(x); yield return x; } } or some suchAnonymous
February 25, 2009
Now I'm confused and curious how this actually compiled and worked. First, Select is lazy, so simply calling Select won't perform the iteration. Second, Select only has Func overloads, and a void method can't be converted to Func. Or do you have some other Select extension method or something? :SAnonymous
February 27, 2009
@DavidNcl - Yes, this is a better approach if you want to use expressions. I believe the Umbrella project has a method like this already. @MichaelGG - You’re exactly right – I posted an update on the original post here: http://www.thejoyofcode.com/Using_Select_instead_of_foreach.aspx - apologies for the mistake and thanks for the feedback.