DangerCoder
DangerCoder

Reputation: 71

Getting the next item in the List<string> based on current item

I have a List<string>, which contains payrollnumbers as strings, e.g.:

 List<string> payrollnumbers = new List<string>() { "0","1","3" };

I want to get the next value in the list, so:

I have the following code, however it does not work like expected:

 List<string> payrollnumbers = new List<string>();
 // fill payrollnumbers ...
 var currpayrollIndex = payrollnumbers.IndexOf(currpayrollnumber);
 var nextPayrollIndex = currpayrollIndex++;
 var payrollnumber = payrollnumbers[nextPayrollIndex];

Upvotes: 0

Views: 257

Answers (3)

juharr
juharr

Reputation: 32266

Because you are using the postfix increment operator (i++) the original value is what gets assigned to nextPayrollIndex before currpayrollIndex is incremented. You could use the prefix increment operator (++i) instead, but I would suggest either making it explicit that you are adding 1 and not increment currpayrollIndex at all.

var nextPayrollIndex = currpayrollIndex + 1;

Or just increment currpayrollIndex and use it instead of nextPayrollIndex.

currpayrollIndex++;
var payrollnumber = payrollnumbers[currpayrollIndex];

I'd also suggest adding checks for when the currpayrollnumber is not in the list (IndexOf will return -1) and when it's the last item (to avoid an ArgumentOutOfRangeException)

Upvotes: 2

blogprogramisty.net
blogprogramisty.net

Reputation: 1762

You have to change:

 var nextPayrollIndex = currpayrollIndex++;

to

var nextPayrollIndex = ++currpayrollIndex;

Is Your solution currpayrollIndex value is increase by 1 after assign to nextPayrollIndex variable

When You change the moment of increase currpayrollIndex by 1 - You first increase by 1 currpayrollIndex value and next assign to nextPayrollIndex variable

It is good explanation here:

What is the difference between i++ and ++i?

Also You may want to change You code to this:

var currpayrollIndex = payrollnumbers.IndexOf(currpayrollnumber);
var payrollnumber = payrollnumbers[++currpayrollIndex ];

it will by more readable

Upvotes: 1

Shadow
Shadow

Reputation: 4006

All you need to do is use ++currpayrollIndex instead of currpayrollIndex++:

var nextPayrollIndex = ++currpayrollIndex;

You can also remove that line entirely and put it in when you access the array:

var payrollnumber = payrollnumbers[++currpayrollIndex];

However it's very unreadable, and might not be noticed by people skimming over the code

Upvotes: 1

Related Questions