如何遍历列表并抓取每个项目
本文关键字:抓取 项目 何遍历 遍历 列表 | 更新日期: 2023-09-27 18:31:47
如何遍历列表并抓取每个项目?
我希望输出看起来像这样:
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));
这就是
我使用更多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}");
});
操作代码的低级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);
}
}
您也可以使用 while 循环来执行此操作
int ctr = 0;
while (ctr <= myMoney.Count - 1)
{
var data = myMoney[ctr];
Console.WriteLine($"{data.amount} - {data.type}");
ctr++;
}