DEV Community

Discussion on: For Loop in different programming languages

Collapse
 
miffpengi profile image
Miff • Edited

Here's the ways to loop a string and an array in C# with a for loop, they're pretty much the same as any other language.

    string str = "hello";
    for (int i = 0; i < str.Length; i++){
        Console.WriteLine(str[i]);
    }

    int[] nums = new int[5];
    for (int i = 0; i < nums.length; i++){
        nums[i] = i;
        Console.WriteLine(i);
    }

However, C# really likes iterators, so those tasks are most commonly done with a foreach loop.

    string str = "hello";
    foreach (char c in str){
        Console.WriteLine(c);
    }

    foreach (int num in Enumerable.Range(0, 5)){
        Console.WriteLine(num);
    }

    // Borrowing from Ben Halpern's example for looping over a collection
    foreach (var topping in pizzaToppings){
        Console.WriteLine("The topping is {0}", topping.Name);
    }
Collapse
 
lobsterpants66 profile image
Chris Shepherd

Then resharper tells you that you can replace that with one line of linq... if my experience is anything to go by 😀