How can I loop through a List<T> and grab each item?

user1929393 picture user1929393 · Sep 18, 2013 · Viewed 583.4k times · Source

How can I loop through a List and grab each item?

I want the output to look like this:

Console.WriteLine("amount is {0}, and type is {1}", myMoney.amount, myMoney.type);

Here is my code:

static void Main(string[] args)
{
    List<Money> myMoney = new List<Money> 
    {
        new Money{amount = 10, type = "US"},
        new Money{amount = 20, type = "US"}
    };
}

class Money
{
    public int amount { get; set; }
    public string type { get; set; }
}

Answer

Simon Whitehead picture Simon Whitehead · Sep 18, 2013

foreach:

foreach (var money in myMoney) {
    Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
}

MSDN Link

Alternatively, because it is a List<T>.. which implements an indexer method [], you can use a normal for loop as well.. although its less readble (IMO):

for (var i = 0; i < myMoney.Count; i++) {
    Console.WriteLine("Amount is {0} and type is {1}", myMoney[i].amount, myMoney[i].type);
}