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!
The SortedList contains the methods necessary to do this. Look at
IndexOfKey
andGetByIndex
.For reference, there are 2 core references for SortedList, one in System.Collections (older) and System.Collections.Generic. When dealing with System.Collections.SortedList, I was only able to use the method of iteration referenced in the Microsoft Article (https://msdn.microsoft.com/en-us/library/system.collections.sortedlist(v=vs.110).aspx)
Here is the loop where myList is the SortedList collection.
Dave
You can use
IndexOfKey
to find the position in the list of the given username.Using the index returned, you can return the next item, or return the first item in the list.
You could try this. Not sure what you want if there is no match so we are just returning an new KeyValuePair; Also make sure you have a using System.Linq; so you have access the ElementAt extension method.
Are you looking for the next item (KeyValuePair), value, or index?
First get the index of the seeking element. Then get the key for the necessary one (don't forget the module
%
). Finally access the loved one :))