News

Copyright © 2008-2019 Paula DiTallo

Tag Cloud



How do I cycle through a Collection?

 

Here are the 2 common patterns in .NET:

GIVEN:

 

PATTERN #1:

Note: this method will work with collections that are typed, but not necessarily defined in a class which manages  enumeration

string itemName;

for (int index = 0; index < OrderList.Count;index++)

{

    itemName = OrderList[index].ItemName;

   // do stuff here

}

PATTERN  #2

 

using System;
using System.Collections.Generic;
using System.Text;

namespace AskPaulaExamples
{
    public class Whine
    {
       // define AND dub the collection with something
       List<string> OrderList = new List<string>() {"Gloves","Purse","Hat","Skirt","Gown"};

       static void Main()
       {
           Whine wailAbout = new Whine();

           wailAbout.StuffForMe();
          
       }

       public void StuffForMe()
       {
           IList<string> MyDemands = OrderList.AsReadOnly();
           foreach (string Item in MyDemands)
           {
               Console.WriteLine("What I want for my BIRTHDAY: " + Item.ToString());
           }
       }
       

     }
}

 

Tuesday, June 16, 2009 9:57 AM

Feedback

# re: How do I cycle through a Collection?

Pattern #3

public void StuffForMe()
{
OrderList.ForEach( order =>
Console.WriteLine("What I want for my BIRTHDAY: " + order.ToString()));
}
7/31/2009 12:34 PM | Scott Rudy

Post A Comment
Title:
Name:
Email:
Comment:
Verification: