C# 如何遍历 List<T> 并抓取每个项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18863187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I loop through a List<T> and grab each item?
提问by user1929393
How can I loop through a List and grab each item?
如何遍历 List 并抓取每个项目?
I want the output to look like this:
我希望输出看起来像这样:
Console.WriteLine("amount is {0}, and type is {1}", myMoney.amount, myMoney.type);
Here is my code:
这是我的代码:
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; }
}
采纳答案by Simon Whitehead
foreach
:
foreach
:
foreach (var money in myMoney) {
Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
}
Alternatively, because it is a List<T>
.. which implements an indexer method []
, you can use a normal for
loop as well.. although its less readble (IMO):
或者,因为它是一个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);
}
回答by Khan
Just like any other collection. With the addition of the List<T>.ForEach
method.
就像任何其他收藏一样。随着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));
回答by acarlon
Just for completeness, there is also the LINQ/Lambda way:
为了完整起见,还有 LINQ/Lambda 方式:
myMoney.ForEach((theMoney) => Console.WriteLine("amount is {0}, and type is {1}", theMoney.amount, theMoney.type));
回答by Coder Absolute
This is how I would write using more functional way
. Here is the code:
这就是我使用 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}");
});