Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<> Get Next element or get the first

Tags:

c#

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 :)

like image 716
The real napster Avatar asked Apr 22 '09 11:04

The real napster


People also ask

Why does adding a new value to list <> overwrite previous values in the list <>?

Essentially, you're setting a Tag's name to the first value in tagList and adding it to the collection, then you're changing that same Tag's name to the second value in tagList and adding it again to the collection. Your collection of Tags contains several references to the same Tag object!

How do you find the next element in a list?

Get Next Element in Python List using next() First of all, convert the list into the iterative cycle using cycle() method. For that, you have to import the cycle from itertools which come preinstalled with Python. Then use the next() method to find the next element in the Python iterator.

Do lists have indexes C#?

The IndexOf method returns the first index of an item if found in the List. C# List<T> class provides methods and properties to create a list of objects (classes). The IndexOf method returns the first index of an item if found in the List.


1 Answers

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.

like image 197
Paul Alexander Avatar answered Sep 29 '22 11:09

Paul Alexander