Is there an equivalent to range(arrayname) in c# like there is in python?

Viewed 246

I have recently started working in C# and have come from a coding background in python. In python there is a way to loop through an array and set variable i to the number in the range for i in range(numbers) This would loop through the array setting i to the index in the array/list. Is there an equivalent in c# or do you have to use a counter to increment each time?

4 Answers

You can use a foreach statement:

foreach (int i in numbers)
{
    // Do something with i
}

You could use foreach to array and lists, but for numbers use this:

for (int = /* start */; i < /* end, exclusive */; i++)
{
    // do something
} 

You can simply use a for loop:

for (var i = 0; i < myArray.Length; i++)
{
    myArray[i] = 0;
}

If you want it the python way then the equivalent for Python's range(...) in C# is Enumerable.Range(...)

Then you can use the enumerable in a foreach loop.

var range = Enumerable.Range(0, myArray.Length);
foreach (var i in range)
{
    myArray[i] = 0;
}

For those who enjoy using linq expressions and don't have too much logic to fit inside the for loop, you can also use this approach:

Enumerable
    .Range(0, 10)
    .Where(x => IsEven(x))
    .Select(x => DoSomethingWithEvenElement(x));

Description:

This first creates a range, then filters elements out by passing them to:

bool IsEven(int x)

and then iterates the remaining values using Select which will pass each element to:

TReturn DoSomethingWithEvenElement(int x)

Related