Как я могу пройти через List <T> и захватить каждый элемент?
Как я могу перебирать список и захватывать каждый элемент?
Я хочу, чтобы результат выглядел следующим образом:
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; }
}
Ответы
Ответ 1
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);
}
Ответ 2
Просто для полноты, есть также способ LINQ/Lambda:
myMoney.ForEach((theMoney) => Console.WriteLine("amount is {0}, and type is {1}", theMoney.amount, theMoney.type));
Ответ 3
Как и любая другая коллекция. С добавлением метода 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));
Ответ 4
Вот как я буду писать, используя больше 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}");
});
Ответ 5
Попробуйте это
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);
}