❔ New to C#

Can somebody tell me what does 'foreach' loop mean? I search on Chinese Internet,but there isn't any useful informations for new. Thank you.
6 Replies
Thinker
Thinker2y ago
A foreach loop executes some code for each element of a list or array. Works like this
List<int> list = new() { 1, 2, 3, 4, 5 };

foreach (int element in list)
{
Console.WriteLine(element);
}
List<int> list = new() { 1, 2, 3, 4, 5 };

foreach (int element in list)
{
Console.WriteLine(element);
}
Here we create a list, then loop through every element of it and print it to the console.
MODiX
MODiX2y ago
thinker227#5176
REPL Result: Success
List<int> list = new() { 1, 2, 3, 4, 5 };

foreach (int element in list)
{
Console.WriteLine(element);
}
List<int> list = new() { 1, 2, 3, 4, 5 };

foreach (int element in list)
{
Console.WriteLine(element);
}
Console Output
1
2
3
4
5
1
2
3
4
5
Compile: 522.117ms | Execution: 49.000ms | React with ❌ to remove this embed.
mr_xiaochen
mr_xiaochen2y ago
@thinker227 Oh,just like this in Python
list = [1,2,3,4,5]
for i in list:
print(list[i])
list = [1,2,3,4,5]
for i in list:
print(list[i])
thank you
Thinker
Thinker2y ago
yep
Messiah
Messiah2y ago
ruguo ni you wenti, keyi wen wo .
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.