How to get the next element in a list?

Hey folks,
I have this function:

     int DecideNumberOfSlots ()
	int noOfSlots = 0;
	List<int> storedID = new List<int> ();

	for (int i = 1; i < cmManager.playerArmyList.Count; i++) {
			if (!storedID.Contains (cmManager.playerArmyList *.ID)) {*

_ if (cmManager.playerArmyList .ID != cmManager.playerArmyList [ i + 1 ].ID) {_
_ storedID.Add (cmManager.playerArmyList .ID);
* noOfSlots++;
return noOfSlots;
which is supposed to count how the different troop types in the list by their IDs, however this code was working perfectly then suddenly stopped and gave me (argument out of range error), when I made (i = 1) and (cmManager.playerArmyList [ i - 1 ].ID) it works but always returns zero if their is only one type of troops.
Any ideas how could I acces the next element in the list or just improve the code?

If you just want to know how many different IDs are in ArmyList, this code would be simpler:

int DecideNumberOfSlots () {
    List<int> storedID = new List<int> (); // create a temporary list of IDs
    for (int i = 0; i < cmManager.playerArmyList.Count; i++) {
        int id = cmManager.playerArmyList*.ID; // get the ID only once*

if (!storedID.Contains(id)){ // if not yet in the list…
storeID.Add(id); // add it
return storedID.Count; // the list size is the number of different IDs
I didn’t get it why you’re comparing each element with the next one before adding a new ID to the list: besides causing the “out of range” error, this could make you miss the last ID.

This is messy. But a quick fix:

None of this makes sense unless there’s more than one thing in the list right?

Test that there is at least 2 things in the list before you do any of this. It will be even messier.

try this style


its at least easier to see whatsup.

I think I got it:
Should make a new list and loop through thr army list then add every id that isn’t in the new list, this isn’t tested yet but I think it will work.
If anybody disagree with the logic please comment why

private int DecideNumberOfSlots()
return cmManager.playerArmyList.Select(f => f.ID).Distinct().Count();
You could maybe try something like this, returns the count of the unique Id’s
Make sure you reference using System.Linq;