use*_*393 156 c# collections for-loop
如何循环列表并抓取每个项目?
我希望输出看起来像这样:
Console.WriteLine("amount is {0}, and type is {1}", myMoney.amount, myMoney.type);
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
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; }
}
Run Code Online (Sandbox Code Playgroud)
Sim*_*ead 253
foreach:
foreach (var money in myMoney) {
Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
}
Run Code Online (Sandbox Code Playgroud)
或者,因为它是一个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);
}
Run Code Online (Sandbox Code Playgroud)
aca*_*lon 32
为了完整起见,还有LINQ/Lambda方式:
myMoney.ForEach((theMoney) => Console.WriteLine("amount is {0}, and type is {1}", theMoney.amount, theMoney.type));
Run Code Online (Sandbox Code Playgroud)
Kha*_*han 16
就像任何其他系列一样.随着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));
Run Code Online (Sandbox Code Playgroud)
Cod*_*ute 11
这就是我要用更多东西写的方式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}");
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
504350 次 |
| 最近记录: |