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

前端 未结 4 1281
难免孤独
难免孤独 2020-11-28 23:02

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         


        
相关标签:
4条回答
  • 2020-11-28 23:31

    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));
    
    0 讨论(0)
  • 2020-11-28 23:31

    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}");
    });
    
    0 讨论(0)
  • 2020-11-28 23:33

    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));
    
    0 讨论(0)
  • 2020-11-28 23:44

    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);
    }
    
    0 讨论(0)
提交回复
热议问题