- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort KeyValuePairs in C#
Use the Sort method to sort the KeyValuePairs collection.
Firstly, set the collection −
var myList = new List<KeyValuePair<int, int>>(); // adding elements myList.Add(new KeyValuePair<int, int>(1, 20)); myList.Add(new KeyValuePair<int, int>(2, 15)); myList.Add(new KeyValuePair<int, int>(3, 35)); myList.Add(new KeyValuePair<int, int>(4, 50)); myList.Add(new KeyValuePair<int, int>(5, 25));
To sort, use the Sort() method. With that, we have used the CompareTo() method to compare values −
myList.Sort((x, y) => (y.Value.CompareTo(x.Value)));
The following is the complete code −
Example
using System; using System.Collections.Generic; class Program { static void Main() { var myList = new List<KeyValuePair<int, int>>(); // adding elements myList.Add(new KeyValuePair<int, int>(1, 20)); myList.Add(new KeyValuePair<int, int>(2, 15)); myList.Add(new KeyValuePair<int, int>(3, 35)); myList.Add(new KeyValuePair<int, int>(4, 50)); myList.Add(new KeyValuePair<int, int>(5, 25)); Console.WriteLine("Unsorted List..."); foreach (var val in myList) { Console.WriteLine(val); } // Sort Value myList.Sort((x, y) => (y.Value.CompareTo(x.Value))); Console.WriteLine("Sorted List..."); foreach (var val in myList) { Console.WriteLine(val); } } }
Output
Unsorted List... [1, 20] [2, 15] [3, 35] [4, 50] [5, 25] Sorted List... [4, 50] [3, 35] [5, 25] [1, 20] [2, 15]
Advertisements