简体   繁体   中英

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)?

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);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM