How to sort a KeyValuePairs list in descending (reverse) order based on the value in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main()
        {
            var list = new List<KeyValuePair<int, int>>()
            {
                new KeyValuePair<int, int>(3, 1),
                new KeyValuePair<int, int>(6, 3),
                new KeyValuePair<int, int>(1, 7),
                new KeyValuePair<int, int>(2, 4)
            };

            list.Sort((a, b) => (b.Value.CompareTo(a.Value)));

            foreach (var kv in list) {
                Console.WriteLine(kv);
            }
        }
    }
}


/*
run:
   
[1, 7]
[2, 4]
[6, 3]
[3, 1]
 
*/

 



answered Aug 24, 2018 by avibootz
...