Geeks With Blogs
Brian Schroer Don't Call Me Mort!
I just stumbled across the new .ForEach methods in .NET 2.0 for Array and the new generic collection objects. Instead of:
    GeekWithBlog[] geeks = GetGeekArray();

    foreach (GeekWithBlog geek in geeks)
    {
        RaiseSalary(geek);
    }
}

private void RaiseSalary(GeekWithBlog geek)
{
    geek.Salary *= 2;
}
... you can now code:
    GeekWithBlog[] geeks = GetGeekArray();

    Array.ForEach(geeks, RaiseSalary);

}

private void RaiseSalary(GeekWithBlog geek)
{
    geek.Salary *= 2;
}
Combined with anonymous methods, this could either make for sleeker code. (Or, it could make for Perl-style "write-only" code if overdone.)
 
Update: D'oh! My first post and I was so busy trying to make it look pretty that both code examples were exactly the same. Thanks to those who pointed it out nicely (OK, starting NOW, don't call me Mort). The second example now shows the Array.ForEach method, as I intended.
Posted on Wednesday, February 1, 2006 4:32 AM .NET | Back to top


Comments on this post: .NET 2.0 "ForEach" methods

# re: .NET 2.0 "ForEach" methods
Requesting Gravatar...
What if we want to make some conditions in the for each and after the condition is satisfied we want to exit from that foreach loop.
Left by SA on Feb 28, 2007 4:38 AM

Your comment:
 (will show your gravatar)


Copyright © Brian Schroer | Powered by: GeeksWithBlogs.net