How does C# assign index values to SortedList items

G

Guest

I'm not comprehending how C# assigns indexes to items you add to a SortedList
item. Here's some example code:
sl.Add ("first_item","First Item");
sl.Add ("second_item", "Second Item");
sl.Add ("third_item","third item");
sl.Add ("fourth_item","fourth item");

I then run a FOR loop to print out the index for each item in the
SortedList, and the index values for each item are completely crazy! Here
they are:
first_item = 0
fourth_item = 1
second_item = 2
third_item =3

Since I'm not working with stacks or queue's, I don't believe FIFO or LIFO
is coming into play here...can anyone explain?
 
G

Guest

Thanks to anyone who might have helped;

I figured this one out with a friend..it sorts it via the key value.
 
E

Eric Cadwell

It sorts the keys as the items are added.

fi
fo
s
t

From the help:
The elements of a SortedList are sorted by the keys either according to a
specific IComparer implementation specified when the SortedList is created
or according to the IComparable implementation provided by the keys
themselves. In either case, a SortedList does not allow duplicate keys.

HTH;
Eric Cadwell
http://www.origincontrols.com
 
B

Bob Grommes

A SortedList is kept ordered by the key value, not by the order in which you
add items. That is why your sorted list is in alphabetical order:

first_item
fourth_item
second_item
third_item

If you want to put them in a particular order then set the key accordingly:

s1.Add(1,"First Item");
s1.Add(2,"Second Item");
s1.Add(3,"Third Item");
s1.Add(4,"Fourth Item");

Now all the following are true:

(string)s1[0] == "First Item";
(string)s1[1] == "Second Item";
(string)s1[2] == "Third Item";
(string)s1[3] == "Fourth Item";

.... and so forth.

--Bob
 

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