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

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 に答える