tags:

views:

45

answers:

2

I'm still stuck with using arrays in XSD generated classes, as my XML schema is too complex for xsd2code, which created generics-based generated classes.

Is their any way to tell the cell number of an array when using foreach across it? Is there any way to do so in LINQ?

A: 

I assume that by "cell number" you mean the index of the current item in the array.

If so, the answer is yes.

For a for loop, you can declare an integer variable and increment it in each iteration to track the index.

For example:

int index = 0;
foreach(var thing in things) {
    //...

    index++;
}


In LINQ, you can call the overloads of Select and Where that take 2-parameter lambdas, like this:

array.Select((elem, index) => whatever);
SLaks
Thanks SLaks for the quick response. The first way is the common way and I was looking for summat neater. Bob.
scope_creep
A: 

You can certainly do it in LINQ:

foreach (var item in Items.Select((elem, index) => new { Item = elem, Index = index }))
{
    DoStuff(item.Item, item.Index);
}
Craig Stuntz
Thanks Craig for the quick response. Bob.
scope_creep