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?
Asked
Active
Viewed 415 times
0
-
http://stackoverflow.com/questions/1250281/c-sharp-how-to-sort-a-sorted-list-by-its-value-column – Dave Ziegler Nov 22 '13 at 04:46
-
You can do a foreach while shifting the values, or do a extension method to make it for flexible. – DevEstacion Nov 22 '13 at 04:50
-
Or use 2 sortedlists add the key/value to one list, swap them and add them to the other list. This way everything is handled in the original enumeration. Assuming, of course, that your data doesn't have millions of entries – tinstaafl Nov 22 '13 at 04:53
-
@tinstaafl yeah that is what I thought of in my solution as well. I was asking to see if there are other ways to do this same thing. I guess that is the simplest and easiest way. – Harris Calvin Nov 22 '13 at 04:58
-
@HarrisCalvin i provided you with a better one below using extension method and generics – DevEstacion Nov 22 '13 at 05:05
-
@RonaldEstacion How is it better when it takes an extra enumeration and you still end up with 2 lists? – tinstaafl Nov 22 '13 at 05:26
-
@tinstaafl any idea how I can fix my errors? – Harris Calvin Nov 22 '13 at 06:15
-
what errors are you getting? – tinstaafl Nov 22 '13 at 12:27
1 Answers
0
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;
}
}

DevEstacion
- 1,947
- 1
- 14
- 28
-
@HarrisCalvin where is it?, also if you're on net 4.0 maybe you can use the task parallel library to speed it up even more. – DevEstacion Nov 22 '13 at 06:24