Renumbering keys in a SortedList

  • Thread starter Thread starter Pekka
  • Start date Start date
P

Pekka

Could somebody say why the piece of code below does not work? My purpose
is to renumber keys in a SortedList (after removal of an item) so that
the keys would always contain an unbroken sequence of integers starting
with 1. For some reason this is not the result.

IDictionaryEnumerator dictEnum = sortedList.GetEnumerator();

int i=1;
while ( dictEnum.MoveNext() ) {
DictionaryEntry de = (DictionaryEntry) dictEnum.Current;
de.Key = i++;
}

With best regards
Pekka
 
Pekka said:
Could somebody say why the piece of code below does not work? My purpose
is to renumber keys in a SortedList (after removal of an item) so that
the keys would always contain an unbroken sequence of integers starting
with 1. For some reason this is not the result.

I don't think any of the .Net datastructures supports simulatneous
enumeration and editing.
IDictionaryEnumerator dictEnum = sortedList.GetEnumerator();
int i=1;
while ( dictEnum.MoveNext() ) {
DictionaryEntry de = (DictionaryEntry) dictEnum.Current;
de.Key = i++;
}

The above is equivalent to the rather prettier:

int i = 1;
foreach ( DictionaryEntry e in sortedList )
e.Key = i++;

I would think you would need to do:

IDictionary new_list = new SortedList(sortedList.Count);
int i = 1;
foreach ( DictionaryEntry e in sortedList )
new_list.Add(i++, e.Value);
sortedList = new_list

But seriously, the items are already sorted in sortedList, and there is
no way lookup the Key from a Value. The keys are obviously not related
to the values, so would you not much rather use a simple array of the
values?

object[] values = new object[sortedList.Count];
sortedList.Values.CopyTo(values, 0);

which you can lookup by integer keys *very* efficiently ;)
 
But seriously, the items are already sorted in sortedList, and there is
no way lookup the Key from a Value. The keys are obviously not related
to the values, so would you not much rather use a simple array of the
values?

object[] values = new object[sortedList.Count];
sortedList.Values.CopyTo(values, 0);

which you can lookup by integer keys *very* efficiently ;)

That's a nice idea :-) Thanks!

Pekka
 
Back
Top