xglide
xglide

Reputation: 65

SortedList<int, int> sort by Value

I've been looking all over and haven't really been able to find a straight answer so here goes:

So let's say I have a SortedList with a Key and a Value where the Key will be unique but the Value won't be guaranteed to be unique. With this I want to have this list sorted by value in ascending order.

Is this possible to do with a comparer and if there isn't a way to do this, what alternative data structure can I use that'll do this relatively quickly and without using much memory(and would be relatively painless to implement)?

Upvotes: 1

Views: 4771

Answers (1)

Rohit
Rohit

Reputation: 10236

here is a simple stand alone example that does what you want

     SortedList<int, string> sortedlist = new SortedList<int, string>();
            //add the elements in sortedlist
            sortedlist.Add(1, "Sunday");
            sortedlist.Add(2, "Monday");
            sortedlist.Add(3, "Tuesday");
            sortedlist.Add(4, "Wednesday");
            sortedlist.Add(5, "Thusday");
            sortedlist.Add(6, "Friday");
            sortedlist.Add(7, "Saturday");
            //display the elements of the sortedlist
            Console.WriteLine("The elements in the SortedList are:");
            foreach (KeyValuePair<int, string> pair in sortedlist)
            {
                Console.WriteLine("{0} => {1}", pair.Key, pair.Value);
            }

            var orderByVal = sortedlist.OrderBy(v => v.Value);

            //display the elements of the sortedlist after sorting it with Value's
            Console.WriteLine("The elements in the SortedList after sorting :");
            foreach (KeyValuePair<int, string> pair in orderByVal)
            {
                Console.WriteLine("{0} => {1}", pair.Key, pair.Value);
            }

Upvotes: 2

Related Questions