Index in Foreach

I am using foreach currently and need an element index.

           foreach (DataRow m_row in base_rows)
       {
           Company nu = new Company(m_row, symb_rows[0]);
       }

Here is the code.

I am trying to get the m_row index inside base_rows and use it to traverse symb_rows[index_of_m_row]. Is this possible, or should I use a regular loop?

+3
source share
7 answers

The "for" lattice solution is perfectly clear. As an interesting alternative solution, you can generally avoid the loop:

var companies = baseRows
  .Select((row, index) => new Company(row, symbRows[index]))
  .ToList();
+11
source

To find out your current index in a collection (using foreach), you should do this:

Int32 i = 0;
foreach (DataRow m_row in base_rows)
{
    Company nu = new Company(m_row, symb_rows[i]);
    i++;
}

for. IEnumerable , .

+7

for , . for-loop.

+1

- , .

+1

, , for() {}. :)

public static void ForEachWithIndex<T>(this IEnumerable<T> items, Action<T, int> render)
{
    if (items == null)
        return;
    int i = 0;
    items.ForEach(item => render(item, i++));
}

base_rows.ForEachWithIndex((m_row, index) => {
    Company nu = new Company(m_row, symb_rows[index]);
});

, , for-loop ;)

+1

.

int , , for( int i = 0.... .

0

Perhaps I would consider using the IndexOf () method as follows:

foreach(DataRow m_row in base_rows)
    Company nu = new Company(m_row, symb_rows.IndexOf(m_row));

You may need to use Array.IndexOf () instead, this worked in VBNET2008 since I am working with it now, but I have not tested it in C #.

For Each DataRow m_row in base_rows
    Company nu = New Company(m_row, symb_rows(Array.IndexOf(symb_rows, m_row)))
Next

So I could suggest the following in C #.

foreach (DataRow m_row in base_rows)
    Company nu = new Company(m_row, symb_rows[Array.IndexOf(symb_rows, m_row)]);

Otherwise, you can use instead of for (;;) instead, sometimes it's better to do it.

for(int index = 0; index < base_rows.Length && index < symb_rows.Length; ++index)
    Company nu = new Company(base_rows[index], symb_rows[symb_rows.IndexOf(base[index])]);

I do not know what you prefer.

0
source

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


All Articles