- Home /
The question is answered, right answer was accepted
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 [i].ID)) {
if (cmManager.playerArmyList [i].ID != cmManager.playerArmyList [ i + 1 ].ID) {
storedID.Add (cmManager.playerArmyList [i].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?
Thanks
Answer by aldonaletto · Jul 08, 2017 at 01:31 AM
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[i].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.
Answer by Jwizard93 · Jul 07, 2017 at 11:42 PM
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
if
{
if
{
}
}
its at least easier to see whatsup.
Answer by abdo400 · Jul 08, 2017 at 12:03 AM
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
Answer by ShadyProductions · Jul 08, 2017 at 12:12 AM
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;