如何滚动列表并捕获每个元素?

如何走在列表中并捕获每个元素?

我希望结果看起来像这样:


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; }
}


</money></money>
已邀请:

窦买办

赞同来自:

foreach

:


foreach /var money in myMoney/ {
Console.WriteLine/"Amount is {0} and type is {1}", money.amount, money.type/;
}


http://msdn.microsoft.com/en-u ... .aspx
或者因为它是
List<t>

.. 它实现了索引器方法
[]

, 您也可以使用通常的周期。
for

.. 虽然他的可读性较小 /IMO/:


for /var i = 0; i &lt; myMoney.Count; i++/ {
Console.WriteLine/"Amount is {0} and type is {1}", myMoney[i].amount, myMoney[i].type/;
}


</t>

郭文康

赞同来自:

只是为了完整的图片,还有一种方式 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 &lt; myMoney.Count; i++/
Console.WriteLine/"amount is {0}, and type is {1}", myMoney[i].amount, myMoney[i].type/;

myMoney.ForEach/item =&gt; Console.WriteLine/"amount is {0}, and type is {1}", item.amount, item.type//;


</t>

帅驴

赞同来自:

这就是我如何使用更多的方式
functional way

. 这段代码:


new List<money>//
{
new Money// { Amount = 10, Type = "US"},
new Money// { Amount = 20, Type = "US"}
}
.ForEach/money =&gt;
{
Console.WriteLine/$"amount is {money.Amount}, and type is {money.Type}"/;
}/;


</money>

要回复问题请先登录注册