我怎样才能通过一个列表与LT回路; T>并抓住每一个项目? [英] How can I loop through a List<T> and grab each item?

查看:101
本文介绍了我怎样才能通过一个列表与LT回路; T>并抓住每一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遍历列表以及如何可以抓住每一个项目?



我所要的输出是这样的:

 控制台。的WriteLine(金额为{0}和类型为{1},myMoney.amount,myMoney.type); 

下面是我的代码:

 静态无效的主要(字串[] args)
{
名单,LT;金钱与GT; myMoney =新的List<金钱与GT; {
新资金量{= 10,键入=US},
新资金量{= 20,键入=US}};
}

类货币
{
公众诠释量{搞定;组; }
公共字符串类型{搞定;组; }
}


解决方案

的foreach

 的foreach(在myMoney VAR钱){
Console.WriteLine( 金额为{0}和类型为{1},money.amount,money.type);
}

MSDN链接



此外,因为它是一个列表< T> ..它实现了一个索引方法 [] ,你可以使用普通的环路以及..虽然它少readble(IMO):

 为(VAR I = 0; I< myMoney.Count; i ++在){
Console.WriteLine(金额为{0}和类型为{1},myMoney [I] .amount,myMoney [I] .TYPE);
}


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

解决方案

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

这篇关于我怎样才能通过一个列表与LT回路; T&GT;并抓住每一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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