I have a quick application in which I wanted to use a SortedList. Having not used this much, I did a little research to make sure I knew what I was doing, and come to discover there are apparently two versions. Or is it that there is one SortedList with additional features? You find one version is System.Collections and the other in System.Collections.Generic.
System.Collections.SortedList slist1 = new SortedList();
System.Collections.Generic.SortedList<string, object> slist2 = new SortedList<string, object>();
They differ in a number of respects. For one thing, slist1 has a method SetByIndex that slist2 doesn't.
So, why are there two versions of the SortedList? And how do you update the value of an object in the Generic SortedList?
答案 0 :(得分:5)
The non-generic class - System.Collections.SortedList
- is one of the classes that was created in the very early days of .NET, before generics were added.
This is the source of most, if not all, of the classes in that namespace, at least if they have generic alternatives.
The generic versions were added later, when, or after generics was added and is usually now the go-to data structures of choice.
System.Collections.SortedList
harkens back to .NET 1.1System.Collections.Generic.SortedList<..>
was added in .NET 2.0答案 1 :(得分:2)
System.Collections.SortedList
is older, it is from .NET 1.1, back before generics where supported. System.Collections.Generic.SortedList<TKey, TValue>
was introduced with .NET 2.0 and normally should be used instead.
Think of them as equivlant to System.Collections.ArrayList
vs System.Collections.Generic.List<TValue>
.
To update the generic version you need to use the indexer
slist2["SomeKeyString"] = newValue;
Or use the Keys
property to get the key if you want to look up by numerical index
slist2[slist2.Keys[2]] = newValue;
Note: this will likely give poorer performance than the non generic version because the TValue this[TKey index]
will need to do a binary search to do a lookup, SetByIndex
could do a direct array access
One final note, a SortedList<Tkey,TValue>
is really only useful if you are going to be enumerating the list in a foreach
and need a order to be maintained, if the order in a foreach
does not matter use a Dictionary<TKey, TValue>
instead and you will get faster insertions and lookups.
答案 2 :(得分:2)
System.Collections.SortedList
goes back to version 1.1 of .NET, before there were generic classes. It's still there because legacy code might be recompiled using a newer framework version so it needs to be in there.
To update the value of an object in a generic SortedList
myGenericSortedList["key"] = "value";