Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; } } 
like image 807
user1929393 Avatar asked Sep 18 '13 03:09

user1929393


People also ask

How to loop list items in C#?

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.

How do you iterate through a list in Python?

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.

Do lists have indexes C#?

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.


2 Answers

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); } 
like image 78
Simon Whitehead Avatar answered Oct 03 '22 17:10

Simon Whitehead


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)); 
like image 45
acarlon Avatar answered Oct 03 '22 17:10

acarlon