如何循环遍历List< T>并抓住每个项目? [英] How can I loop through a List<T> and grab each item?

查看:494
本文介绍了如何循环遍历List< T>并抓住每个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何循环遍历列表并抓取每个项目?

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

这是我的代码:

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


推荐答案

foreach

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

MSDN链接

或者,因为它是 List< T& / code> ..它实现了一个索引器方法 [] ,你可以使用正则作为虽然它的readble(IMO):

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

这篇关于如何循环遍历List&lt; T&gt;并抓住每个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆