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

C#For LoopCollections

C# Problem Overview


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; }
}

C# Solutions


Solution 1 - C#

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);
}

Solution 2 - C#

Just for completeness, there is also the LINQ/Lambda way:

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

Solution 3 - C#

Just like any other collection. With the addition of the List<T>.ForEach method.

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

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

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

Solution 4 - C#

This is how I would write using more functional way. Here is the code:

new List<Money>()
{
	 new Money() { Amount = 10, Type = "US"},
	 new Money() { Amount = 20, Type = "US"}
}
.ForEach(money =>
{
	Console.WriteLine($"amount is {money.Amount}, and type is {money.Type}");
});

Solution 5 - C#

The low level iterator manipulate code:

List<Money> myMoney = new List<Money>
{
	new Money{amount = 10, type = "US"},
	new Money{amount = 20, type = "US"}
};
using (var enumerator = myMoney.GetEnumerator())
{
	while (enumerator.MoveNext())
	{
		var element = enumerator.Current;
		Console.WriteLine(element.amount);
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1929393View Question on Stackoverflow
Solution 1 - C#Simon WhiteheadView Answer on Stackoverflow
Solution 2 - C#acarlonView Answer on Stackoverflow
Solution 3 - C#KhanView Answer on Stackoverflow
Solution 4 - C#Coder AbsoluteView Answer on Stackoverflow
Solution 5 - C#yu yang JianView Answer on Stackoverflow