The real napster The real napster - 11 days ago 8
C# Question

List<> Get Next element or get the first

I want to get the next element in a list and if the list is at it's end I want the first element.
So I just want it to circle in other words.

List<int> agents = taskdal.GetOfficeAgents(Branches.aarhusBranch);
if (lastAgentIDAarhus != -1)
{
int index = agents.IndexOf(lastAgentIDAarhus);
if (agents.Count > index + 1)
{
lastAgentIDAarhus = agents[index + 1];
}
else
{
lastAgentIDAarhus = agents[0];
}
}
else
{
lastAgentIDAarhus = agents[0];
}


I am fairly displeased with my own solution shown above, let me know if you have a better one :)

Answer
lastAgentIDAarhus = agents[index == -1 ? 0 : index % agents.Count];

The use of the MOD operator % atuomatically chops the index to the range of possible indexes.

The modulo operator is the compliment to the DIV (/) operator and returns the remainder of a division of two whole numbers. For example if you divide 9 by 6 the result is 1 with a remainder of 3. The MOD operator asks for the 3.