207

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

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

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

5 回答 5

318

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);
}
于 2013-09-18T03:08:14.467 回答
40

为了完整起见,还有 LINQ/Lambda 方式:

myMoney.ForEach((theMoney) => Console.WriteLine("amount is {0}, and type is {1}", theMoney.amount, theMoney.type));
于 2013-09-18T03:42:30.690 回答
20

就像任何其他收藏一样。加上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));
于 2013-09-18T03:13:48.963 回答
14

这就是我使用 more 编写的方式functional way。这是代码:

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}");
});
于 2017-10-31T06:37:41.703 回答
1

低级iterator操作代码:

List<Money> myMoney = new List<Money>
{
    new Money{amount = 10, type = "US"},
    new Money{amount = 20, type = "US"}
};
using (var enumerator = myMoney.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        var element = enumerator.Current;
        Console.WriteLine(element.amount);
    }
}
于 2021-01-22T13:28:10.297 回答