小编典典

如何循环遍历列表并抓住每件物品?

all

如何遍历列表并获取每个项目?

我希望输出看起来像这样:

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

这是我的代码:

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

阅读 73

收藏
2022-06-22

共1个答案

小编典典

foreach

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

MSDN 链接

或者,因为它是一个List<T>实现索引器方法的 .. ,所以[]您也可以使用普通for循环 .. 虽然它的可读性较差(IMO):

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