[英]How can I loop through a List<T> and grab each item?
How can I loop through a List and grab each item?如何遍历列表并获取每个项目?
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; }
}
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);
}
为了完整起见,还有 LINQ/Lambda 方式:
myMoney.ForEach((theMoney) => Console.WriteLine("amount is {0}, and type is {1}", theMoney.amount, theMoney.type));
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));
This is how I would write using more functional way
.这就是我将使用更functional way
。 Here is the code:这是代码:
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}");
});
The low level iterator
manipulate code:低级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);
}
}
Try this 试试这个
List<int> mylist = new List<int>();
mylist.Add(10);
mylist.Add(100);
mylist.Add(-1);
// We can loop over list items with foreach. //我们可以使用foreach遍历列表项。
foreach (int value in mylist )
{
Console.WriteLine(value);
}
Console.WriteLine("::DONE WITH PART 1::");
// This will cause an enter code here
exception. //这将导致enter code here
异常。
foreach (int value in mylist )
{
list.Add(0);
}
You can also do it using the while loop您也可以使用 while 循环来执行此操作
int ctr = 0;
while (ctr <= myMoney.Count - 1)
{
var data = myMoney[ctr];
Console.WriteLine($"{data.amount} - {data.type}");
ctr++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.