C# Sort KeyValuePair List

KeyValuePair (Key and Value properties)

You want to sort a collection of KeyValuePair struct instances in your C# program. Using an enclosing List collection, you can implement Comparison delegates as static int methods.

Example

This example code introduces three static methods: the Compare1 method, which receives two KeyValuePair structs and returns the result of CompareTo on their Key; the Compare2 method, which returns the CompareTo of the Value; and the Main entry point.

KeyValuePair Hints Main Args Examples

This C# example program shows how to sort KeyValuePair structs in a List.

Program that sorts List of KeyValuePair instances [C#]

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

Output

[Dot, 8]
[Net, 9]
[Perl, 7]

[Perl, 7]
[Dot, 8]
[Net, 9]
List type.

Description. Please look at the contents of the Main entry point. 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. After printing the List, we sort it again with Compare2, and finally display the List again.

List Examples

Results. The List.Sort(Compare1) call sorts the List by the Key of the KeyValuePair; this is due to the implementation of Compare1. The List.Sort(Compare2) call, meanwhile, sorts the List by the Value int.

Sort List Method

Summary

The C# programming language

With this example program, we implemented one way of sorting collections of KeyValuePair instances. You can use other syntax forms and implementations, such as LINQ expressions or lambda expressions, to accomplish this task as well.

OrderBy Clause Lambda Expression Sort Examples
.NET