Using the foreach (...) syntax, as well as increasing the index variable inside the loop

When viewing C # code, I often see these patterns:

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 loops through the objects in items, but also maintains a counter ( i) to iterate over itemProps. I personally don't like this extra ione hanging around, and instead will 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;
}

Maybe there are some advantages to the first approach, which I do not know about? Is this the result of everyone trying to use this fancy syntax foreach (...)? I'm interested in your opinions on this matter.

+3
source share
7 answers

If you use C # 3.0, which will be better,

OtherDataType[] itemProps = items.Select(i=>i.Prop).ToArray();
+7

i, , , . , .Count .UBound, .

, , .

+4

. , , this[int index], GetEnumerator(). .

+2

, (, ..). , , - , ...

+1

, foreach .

, Effective #, .

+1

foreach ( DataType ) foreach , DataType, , . , , "" . for-loop , , .

, , ... .. " " "-foreach, , , (int = 0; i...). (, , , 2)

, , Vim vs Emacs For vs Foreach:) , for(), , foreach , . , foreach, - , , , .

, .. ?! , foreach, . , , foreach, , . , =. , . , , ++ : D , Vim!

+1

Do not forget that some collections do not implement the direct access operator [], and you need to iterate through the IEnumerable interface, which is most easily accessed using foreach ().

+1
source

Source: https://habr.com/ru/post/1699455/


All Articles