Keeping the key-values sorted by using a SortedDictionary with C# .NET

You can use the generic SortedDictionary of Key and Value to automatically keep the key value items sorted by their keys. Any time you add a new key value pair the dictionary will reorder the items. The SortedDictionary was optimised for frequent changes to its list of items. Keep in mind that the items will be sorted by their key and not their value.

Consider the following simple custom object:

public class Student
{
	public string Name { get; set; }
	public string SchoolName { get; set; }
}

Let’s organise a couple of students into a sorted dictionary by their birthdates:

SortedDictionary<int, List<Student>> birthDates = new SortedDictionary<int, List<Student>>();
birthDates[1990] = new List<Student>()
{
	new Student()
	{
		Name = "John", 
		SchoolName ="Great school"
	},
	new Student()
	{
		Name = "Diana", 
		SchoolName ="Great school"
	},
	new Student()
	{
		Name = "Peter", 
		SchoolName ="Awesome school"
	}
};

birthDates[1979] = new List<Student>()
{
	new Student()
	{
		Name = "Daniel", 
		SchoolName ="Great school"
	},
	new Student()
	{
		Name = "Hanna", 
		SchoolName ="Awesome school"
	}
};

birthDates[1985] = new List<Student>()
{
	new Student()
	{
		Name = "Daniel", 
		SchoolName ="Awesome school"
	},
	new Student()
	{
		Name = "Hanna", 
		SchoolName ="Great school"
	}
};

foreach (var kvp in birthDates)
{
	Debug.WriteLine(kvp.Key);
}

The code prints the years in ascending order:

1979
1985
1990

Remember though that this is a Dictionary so if you add another key-value with an existing key then the existing key will be overwritten.

This was a simple case as ordering – and uniqueness – is based on an integer key, i.e. the year of birth. .NET can order primitive types like integers in a natural way, we don’t have to give it any help. .NET can also compare primitive types, i.e. it can determine whether two integers or two strings are equal.

However, what if the key is a custom object? Say we’d like to have Student objects as keys and a list of strings as values. The list of strings can store the titles of the essays they have written at school. How will .NET be able to determine the ordering and uniqueness of Student? It cannot of course. We’ll have to declare how two student objects can be ordered and compared. Both can be achieved by overriding the generic IComparable of T interface like we saw in this post. Let’s order the Student objects by their Name properties:

public class StudentNameComparer : IComparer<Student>
{
	public int Compare(Student x, Student y)
	{
		return x.Name.CompareTo(y.Name);
	}
}

The following example shows how you can supply the custom comparer to a sorted dictionary. I’ve ignored assigning school names and the list of essay titles, those are not relevant now:

SortedDictionary<Student, List<string>> essays = new SortedDictionary<Student, List<string>>(new StudentNameComparer());
essays.Add(new Student() { Name = "John" }, new List<string>());
essays.Add(new Student() { Name = "Adam" }, new List<string>());
essays.Add(new Student() { Name = "Paul" }, new List<string>());
essays.Add(new Student() { Name = "Hannah" }, new List<string>());
essays.Add(new Student() { Name = "Eve" }, new List<string>());
essays.Add(new Student() { Name = "Anne" }, new List<string>());
essays.Add(new Student() { Name = "Mary" }, new List<string>());

foreach (var kvp in essays)
{
	Debug.WriteLine(kvp.Key.Name);
}

This prints the names in the correct alphabetical order:

Adam
Anne
Eve
Hannah
John
Mary
Paul

View all various C# language feature related posts here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: