Brian Schroer

Don't Call Me Mort!

  Home  |   Contact  |   Syndication    |   Login
  30 Posts | 0 Stories | 20 Comments | 10 Trackbacks

News

Tag Cloud


Archives

Post Categories

Links

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 01, 2006 4:32 AM

Feedback

# re: .NET 2.0 "ForEach" methods 2/28/2007 4:38 AM SA
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.

Post Feedback

Title:
Name:
Email: (never displayed)
Url:
Comments: 
Please add 8 and 6 and type the answer here: