Home
C#
Sort KeyValuePair List
Updated Dec 7, 2022
Dot Net Perls
Sort KeyValuePair List. A List contains many KeyValuePair struct instances. It can be sorted with the Sort List method. For advanced sorting, we need Comparison.
Comparison info. This code requires Comparison delegate implementations. We implement these as static int methods that call CompareTo.
Comparison
CompareTo
Sort
Example code. Compare1 receives two KeyValuePair structs and returns the result of CompareTo on their Key. Compare2 returns the CompareTo of the Value.
KeyValuePair
Detail A new List of KeyValuePair instances is created. Three KeyValuePairs are created and added to the List.
Next The List is sorted with Compare1. The method target Compare1 is accepted as a Comparison delegate.
Then After printing the List, we sort it again with Compare2, and finally display the List again.
List
Console.WriteLine
using System; using System.Collections.Generic; class Program { static int Compare1(KeyValuePair<string, int> a, KeyValuePair<string, int> b) { return a.Key.CompareTo(b.Key); } static int Compare2(KeyValuePair<string, int> a, KeyValuePair<string, int> b) { return a.Value.CompareTo(b.Value); } static void Main() { var list = new List<KeyValuePair<string, int>>(); list.Add(new KeyValuePair<string, int>("Perl", 7)); list.Add(new KeyValuePair<string, int>("Net", 9)); list.Add(new KeyValuePair<string, int>("Dot", 8)); // Use Compare1 as comparison delegate. list.Sort(Compare1); foreach (var pair in list) { Console.WriteLine(pair); } Console.WriteLine(); // Use Compare2 as comparison delegate. list.Sort(Compare2); foreach (var pair in list) { Console.WriteLine(pair); } } }
[Dot, 8] [Net, 9] [Perl, 7] [Perl, 7] [Dot, 8] [Net, 9]
Program results. The List.Sort(Compare1) call sorts the List by the Key of the KeyValuePair. And the List.Sort(Compare2) call sorts the List by the Value int.
Sort List, Lambda
Compare1 -> Key Compare2 -> Value
A summary. We sorted collections of KeyValuePairs. We can use other syntax forms and implementations, such as LINQ expressions or lambda expressions, to accomplish this task.
orderby
Lambda
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen