如何循环List <T>并抓取每个项目?

use*_*393 156 c# collections for-loop

如何循环列表并抓取每个项目?

我希望输出看起来像这样:

Console.WriteLine("amount is {0}, and type is {1}", myMoney.amount, myMoney.type);
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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; }
}
Run Code Online (Sandbox Code Playgroud)

Sim*_*ead 253

foreach:

foreach (var money in myMoney) {
    Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

  • @awudoin什么?不,它没有..它在堆栈上创建一个引用..除此之外,它没有.`foreach`不克隆对象.. (7认同)
  • 你是对的......它只是一个"枚举器"而不是对象的副本.但事实仍然是,取决于你正在做什么,有一个`foreach`循环与`for`循环的开销更多.我刚刚使用你的代码在`List`中运行了一个带有100,000个条目的快速测试,并且`foreach`循环花费了两倍的长度(实际上是1.9倍).在所有情况下都不一定如此,但在许多情况下.这取决于List的大小,你在循环中做了多少操作等等....这就是我所得到的. (7认同)
  • 我应该澄清一下:它还创建了一个`Enumerator` ..这是一个`struct` ..它也在堆栈中.所以我仍然不太明白你的评论. (2认同)

aca*_*lon 32

为了完整起见,还有LINQ/Lambda方式:

myMoney.ForEach((theMoney) => Console.WriteLine("amount is {0}, and type is {1}", theMoney.amount, theMoney.type));
Run Code Online (Sandbox Code Playgroud)


Kha*_*han 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));
Run Code Online (Sandbox Code Playgroud)

  • 另一个警告,如果你有一个大的列表,(大的意思是超过100,000项)myMoney.Count开始需要一段时间,因为它必须遍历列表来执行计数,并在myMoney上面的示例中.每次循环计数.所以使用int myMoneyC = myMoney.Count; for(int i = 0; i <myMoneyC; i ++)将使循环速度提高许多倍. (6认同)

Cod*_*ute 11

这就是我要用更多东西写的方式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}");
});
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。这是完成此任务的非常短的方法。您还使用了 VS 2017/.NET 4.7 中引入的 writeLine 新的紧凑语法。 (2认同)