我如何通过一个列表循环,并抓住每一个项目?
我希望输出是这样的:
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>..它实现了一个索引器方法[],你也可以使用一个正常的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);
}
就像其他系列一样。随着List<T>的添加。ForEach方法。
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));
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);
}