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; } }
Using foreach Statement The standard option to iterate over the List in C# is using a foreach loop. Then, we can perform any action on each element of the List. The following code example demonstrates its usage by displaying the contents of the list to the console.
You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.
The IndexOf method returns the first index of an item if found in the List. C# List<T> class provides methods and properties to create a list of objects (classes). The IndexOf method returns the first index of an item if found in the List.
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); }
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With