开发者

Index in a Foreach

I'm using a foreach currently, and need the index of the item.

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

Here's the code.

I'm trying to get the index of m_row inside of base_rows and use that to pass symb_rows[index_of_m_row]. Is this po开发者_如何学Pythonssible or should I just use a normal for loop?


The "for" loop solution is perfectly clear. As an interesting alternative solution, you could eschew the loop altogether:

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


In order to know your current index in the collection (using a foreach) you must do this:

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

or use a standard for loop. The IEnumerable interface does not expose a positional index property as it is a forward-only iterator over an underlying sequence of items.


You have to use a normal for-loop or create your own counter like Andrew Hare suggests to get this working. I would suggest using a for-loop.


The absolute best way to solve it is of course to use a for() {} loop instead. But you can get funky and write a extension-method :)

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++));
}

And too use it

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

But then again, maybe a for-loop does the job better ;)


A normal for loop is the way to go if you need the index.


I would just use a normal loop.

You could have an int the increments every time you loop around but a normal for( int i = 0.... would be your best bet.


I would perhaps consider using the IndexOf() method like so:

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

Perhaps will you have to use Array.IndexOf() instead, this worked in VBNET2008, as I'm currently working with it, but I didn't test 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 might 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 might consider using a for(;;) instead, sometimes it's better doing so.

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 don't know which you prefer though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜