Search code examples
c#foreachincrementpost-increment

How do I increment integers inside foreach and statement?


How can I increment an integer inside a foreach loop (like in C++)

This is my code, but it does not increment the selectIndex integer during each loop iteration.

var list = new List<string>();
int selectIndex = 0;

foreach(TType t in Gls.TTypes)
{
    selectIndex = Gls.TType.Name == t.Name ? selectIndex++ : 0;
    list.Add(t.Name);
}

Got it working as follows:

var list = new List<string>();
int selectIndex = 0;
int counter = 0;
foreach(TaxType t in Globals.TaxTypes)
{
    selectIndex = Globals.TaxType.Name == t.Name ? counter : selectIndex;
    counter++;

    list.Add(t.Name);
}

The purpose was to select the matching item in a UIPickerView.

Many thanks to all contributions!


Solution

  • IMHO that pattern you are using here is horrid. Pre and postfix increments modify the value they're invoked upon so it makes no sense to then copy the result (incidentally it's not working because you're copying the value before the postfix increment takes place).

    So you can use solutions like @Vilx- and @KarthikT's - but in my opinion, instead of trying to cram it all on one line I'd much rather see:

    if(Gls.TType.Name == t.Name) 
      selectIndex++;
    else selectIndex = 0;
    

    Don't get me wrong - I use the conditional operator a lot; but I wouldn't in this case.