如何循环浏览列表并抓取每个项目?
我希望输出看起来像这样:
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; }
}
答案 0 :(得分:227)
foreach
:
foreach (var money in myMoney) {
Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
}
或者,因为它是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);
}
答案 1 :(得分:30)
为了完整起见,还有LINQ / Lambda方式:
myMoney.ForEach((theMoney) => Console.WriteLine("amount is {0}, and type is {1}", theMoney.amount, theMoney.type));
答案 2 :(得分: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));
答案 3 :(得分:9)
这是我用更多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}");
});
答案 4 :(得分:0)
尝试一下
List<int> mylist = new List<int>();
mylist.Add(10);
mylist.Add(100);
mylist.Add(-1);
//我们可以使用foreach遍历列表项。
foreach (int value in mylist )
{
Console.WriteLine(value);
}
Console.WriteLine("::DONE WITH PART 1::");
//这将导致enter code here
异常。
foreach (int value in mylist )
{
list.Add(0);
}
答案 5 :(得分:0)
低级 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);
}
}