我如何循环访问List <T>并获取每个项目?
我如何循环访问列表并获取每个项目?
我想要输出如下所示:
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); }
为了完整起见,还有LINQ / Lambda方式:
myMoney.ForEach((theMoney) => Console.WriteLine("amount is {0}, and type is {1}", theMoney.amount, theMoney.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));
这是我将如何使用更多function的方式写。 这里是代码:
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}"); });