Search code examples
c#sortedlist

Iteration through SortedList


SortedList<string, systemuser> Users = new SortedList<string, systemuser>();
Users.Add("username1",customobject);
Users.Add("username2",customobject);
Users.Add("username3",customobject);

What i'm trying to do is search the list for a specific key (i.e. a username) and return the next item in the list. If i'm at the end of the list then I need to return the item in the first position.

Not sure how to go about this, as the SortedList doesn't seem to expose an index property.

I have:

foreach (KeyValuePair<string, systemuser> pair in Users)
{
    if (pair.Key == lastAllocation)
    {
        // RETURN THE ITEM IMMEDIATELY AFTER THIS ONE
    }
}

Any suggestion appreciated!


Solution

  • Are you looking for the next item (KeyValuePair), value, or index?

    bool returnNextItem = false;
    foreach (KeyValuePair<string, systemuser> pair in Users)
    {
        if (returnNextItem)
            return pair.Value;
        if (pair.Key == lastAllocation)
            returnNextItem = true;
    }