Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using foreach (...) syntax while also incrementing an index variable inside the loop

When looking at C# code, I often see patterns like this:

DataType[] items = GetSomeItems();
OtherDataType[] itemProps = new OtherDataType[items.Length];

int i = 0;
foreach (DataType item in items)
{
    // Do some stuff with item, then finally
    itemProps[i] = item.Prop;
    i++;
}

The for-loop iterates over the objects in items, but also keeping a counter (i) for iterating over itemProps as well. I personally don't like this extra i hanging around, and instead would probably do something like:

DataType[] items = GetSomeItems();
OtherDataType[] itemProps = new OtherDataType[items.Length];

for (int i = 0; i < items.Length; i++)
{
    // Do some stuff with items[i], then finally
    itemProps[i] = items[i].Prop;
}

Is there perhaps some benfit to the first approach I'm not aware of? Is this a result of everybody trying to use that fancy foreach (...) syntax? I'm interested in your opinions on this.

like image 491
Mike Mazur Avatar asked Dec 03 '22 16:12

Mike Mazur


2 Answers

If you are using C# 3.0 that will be better;

OtherDataType[] itemProps = items.Select(i=>i.Prop).ToArray();
like image 94
Ali Ersöz Avatar answered Jan 04 '23 22:01

Ali Ersöz


With i being outside the array then if would be available after the completion of the loop. If you wanted to count the number of items and the collection didn't provide a .Count or .UBound property then this could be useful.

Like you I would normally use the second method, looks much cleaner to me.

like image 41
DilbertDave Avatar answered Jan 04 '23 22:01

DilbertDave