Problem with SortedList

C

Curious

Hi,

I am using SortedList, but I am having problems with indexing.

SortedList x = new SortedList();

x.Add(0, "zero");
x.Add(1, "one");
x.Add(3, "three");
Console.WriteLine(x[x.IndexOfKey(0)].ToString());
Console.WriteLine(x[x.IndexOfKey(1)].ToString());
int index = x.IndexOfKey(3);
Console.WriteLine(index);
Console.ReadLine();
Console.WriteLine(x[index].ToString());

The first two writeline work ok, but when I try to retrieve the index
of the key 3, Index of 2 is returned.

Now when I try to use this index(ie index=2) to retrieve the data from
the sortedList, a NullReferenceException is given.


Can someone help me out.
Thanks in Advance
 
L

Larry Lard

Curious said:
Hi,

I am using SortedList, but I am having problems with indexing.

SortedList x = new SortedList();

x.Add(0, "zero");
x.Add(1, "one");
x.Add(3, "three");
Console.WriteLine(x[x.IndexOfKey(0)].ToString());
Console.WriteLine(x[x.IndexOfKey(1)].ToString());
int index = x.IndexOfKey(3);
Console.WriteLine(index);
Console.ReadLine();
Console.WriteLine(x[index].ToString());

The first two writeline work ok, but when I try to retrieve the index
of the key 3, Index of 2 is returned.

Now when I try to use this index(ie index=2) to retrieve the data from
the sortedList, a NullReferenceException is given.

..Item, the indexer property of a SortedList, takes a *key*, not an
index. Therefore when you ask for x[2] you are asking for the value
associated with the *key* 2 - there isn't one, so you get null back.

To get by index, use the .GetByIndex method.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top