Boris
Boris

Reputation: 8931

C# Sorted list: How to get the next element?

I'm wondering how to get the next element in a C# sorted list. SO far I've 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 that's the smartest way to do it ;-)

Upvotes: 14

Views: 20251

Answers (4)

Chris
Chris

Reputation: 1139

SortedList<int, Bla> mList;
int key = 0;
Bla someElement = mList.Values[key];

...
key = 1;
Bla next        = mList.Values[key];

Upvotes: -1

Scott Rippey
Scott Rippey

Reputation: 15810

Since you can access a SortedList by index (see the Remarks section), I'd 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 a single lookup.

Here's also the LINQ way to do it:

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]; 

This will only enumerate once. It will execute in O(n).

Upvotes: 15

parapura rajkumar
parapura rajkumar

Reputation: 24403

SortedList can be accessed by both key and index

var IndexOfKey = mList.IndexOfKey(key);

Increment the index,

IndexOfKey++; //Handle last index case

Get the next item by index.

var nextElement = mList.GetByIndex(IndexOfKey);

Upvotes: 6

Andrey Atapin
Andrey Atapin

Reputation: 7945

Use enumerator:

 IDictionaryEnumerator iterator = mList.GetEnumerator();
 iterator.MoveNext();
 Bla first = iterator.Value;
 iterator.MoveNext();
 Bla next = iterator.Value;

Upvotes: 3

Related Questions