.NET Tip of The Day
Learn one new .NET trick every day
Быстрое пополнение счета телефона      Login or Join

Create elegant code with Action delegate and List.ForEach method

Let's review the following code which works with generic collection:

    List<Tip> tips = new List<Tip>();        //represents a list of Tips

    ...

 

    //create SiteMapNode from each Tip

    foreach (Tip tip in tips)

    {

        string url = string.Format("{0}/tips/{1}.aspx", appPath, tip.Id);

        SiteMapNode node = new SiteMapNode(this, url, url, tip.Title);

        node["lastmod"] = tip.PubDate.ToString("u");

        AddNode(node, rootNode);

    }

Although this code works well we can improve it using Action delegate and List.ForEach method. First we have to exctract code to create SiteMapNode into a method:

    private void AddSiteMapNode(Tip tip)

    {

        string url = string.Format("{0}/tips/{1}.aspx", appPath, tip.Id);

        SiteMapNode node = new SiteMapNode(this, url, url, tip.Title);

        node["lastmod"] = tip.PubDate.ToString("u");

        AddNode(node, rootNode);

    }

Separating it into a separate method has a few advantages, practically the ability to reuse the same logic for other uses. Now once we have this method creating SiteMapNode's from Tips collection would be:

    tips.ForEach(AddSiteMapNode);

P.S. this tip also can be used with Array.ForEach method.

11/11/2007
RSS .NET Tip of The Day
Subscribe to receive one tip from the .NET Tips and Tricks Community per day.
Previous Tips of The Day
The best of the .NET Tips & Tricks Community.
.NET Practitioners .NET Tips & Tricks Community
Every .NET practitioner has a trick up in their sleeve. This is the place to share it with other .NET people.
Submit a Tip
Discovered a new trick? Share it with others.
My Tips
Manage tips you authored.