Pekka wrote:
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 ;)
--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music:
http://ungdomshus.nu <=-