Search code examples
c#sortedlist

Resorting a SortedList by key


I have a SortedList which is obviously sorted by Key. Somewhere down in the code I want to sort it by value instead of the key so do I have to re-insert the SortedList with the value and key swapped? How would I swap the key and value? Create another SortedList and do a foreach loop to load into that?


Solution

  • made this one in a hurry. This will shift the type and return it with the key and value shifted

    public static class Extension
        {
            public static SortedList<TValue, TKey> ShiftKeyValuePair<TKey, TValue>(this SortedList<TKey, TValue> instance)
            {
                SortedList<TValue, TKey> key = new SortedList<TValue, TKey>();
                foreach (var item in instance)
                    key.Add(item.Value, item.Key);
                return key;
            }
        }