C # Sorted list: how to get the next item?

I am wondering how to get the next item in a C # sorted list. So far I have come up with the following code:

SortedList<int, Bla> mList; Bla someElement = mList[key]; Bla next = mList[mList.Keys[mList.IndexOfKey(key) + 1]]; 

I'm not sure if this is the smartest way to do this; -)

+10
source share
4 answers

Since you can access the SortedList using index (see the Notes section) , I would recommend using the following:

 var index = mList.IndexOfKey(key); var first = mList.Values[index]; var second = mList.Values[index + 1]; 

This will work in the same O(log n) as one search.

The LINQ method is also used here:

 var items = mList.SkipWhile(m => m.Key != key).Select(m => m.Value).Take(2).ToList(); // Avoid double-enumeration by calling ToList var first = mList[0]; var second = mList[1]; 

It will be only once. It will execute in O(n) .

+10
source

SortedList can be accessed by key or index

 var IndexOfKey = mList.IndexOfKey(key); 

Increase index

 IndexOfKey++; //Handle last index case 

Get the next item by index.

 var nextElement = mList.GetByIndex(IndexOfKey); 
+6
source

Use enumerator:

  IDictionaryEnumerator iterator = mList.GetEnumerator(); iterator.MoveNext(); Bla first = iterator.Value; iterator.MoveNext(); Bla next = iterator.Value; 
+3
source
 SortedList<int, Bla> mList; int key = 0; Bla someElement = mList.Values[key]; ... key = 1; Bla next = mList.Values[key]; 
0
source

All Articles