Using the KeyedCollection object in C# .NET

The abstract generic KeyedCollection object can be used to declare which field of your custom object to use as a key in a Dictionary. It provides sort of a short-cut where you’d want to organise your objects in a Dictionary by an attribute of that object.

Let’s take the following object as an example:

public class CloudServer
{
	public string CloudProvider { get; set; }
	public string ImageId { get; set; }
	public string Size { get; set; }
}

The Image IDs are always unique so the ImageId property seems to be a good candidate for a dictionary key.

Here’s an example:

Dictionary<string, CloudServer> cloudServers = new Dictionary<string, CloudServer>();
cloudServers.Add("aaa", new CloudServer() { CloudProvider = "Amazon", ImageId = "aaa", Size = "m2.large" });
cloudServers.Add("bbb", new CloudServer() { CloudProvider = "Rackspace", ImageId = "bbb", Size = "large" });
cloudServers.Add("ccc", new CloudServer() { CloudProvider = "Amazon", ImageId = "ccc", Size = "dw2.xlarge" });
cloudServers.Add("ddd", new CloudServer() { CloudProvider = "Azure", ImageId = "ddd", Size = "small" });
cloudServers.Add("eee", new CloudServer() { CloudProvider = "Google", ImageId = "eee", Size = "medium" });
cloudServers.Add("fff", new CloudServer() { CloudProvider = "Azure", ImageId = "fff", Size = "x-large" });

We provide the image ID twice which is both unnecessary and error prone.

One way to remedy the situation is to derive from the abstract KeyedCollection in the System.Collections.ObjectModel namespace object and override its GetKeyForItem method. You’ll only need to provide the way the key can be retrieved. The KeyedCollection object has two generic type parameters. The first one defines the type of the key and the second one the type of the value:

public class CloudServersKeyedDictionary : KeyedCollection<string, CloudServer>
{
	protected override string GetKeyForItem(CloudServer item)
	{
		return item.ImageId;
	}
}

We can rebuild our Dictionary as follows:

CloudServersKeyedDictionary keyedDict = new CloudServersKeyedDictionary();
keyedDict.Add(new CloudServer() { CloudProvider = "Amazon", ImageId = "aaa", Size = "m2.large" });
keyedDict.Add(new CloudServer() { CloudProvider = "Rackspace", ImageId = "bbb", Size = "large" });
keyedDict.Add(new CloudServer() { CloudProvider = "Amazon", ImageId = "ccc", Size = "dw2.xlarge" });
keyedDict.Add(new CloudServer() { CloudProvider = "Azure", ImageId = "ddd", Size = "small" });
keyedDict.Add(new CloudServer() { CloudProvider = "Google", ImageId = "eee", Size = "medium" });
keyedDict.Add(new CloudServer() { CloudProvider = "Azure", ImageId = "fff", Size = "x-large" });

We only had to provide the values in the custom dictionary, they keys will be extracted using the overridden GetKeyForItem method.

You can access the values by their keys like in a normal Dictionary:

CloudServer aaaServer = keyedDict["aaa"];

KeyedDictionary has other methods that you can override to modify the behaviour of your dictionary:

  • InsertItem
  • RemoveItem
  • SetItem
  • ClearItems

You can override the ClearItems and RemoveItem methods to throw an exception in case you don’t want to enable the user to remove items from the dictionary.

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.

One Response to Using the KeyedCollection object in C# .NET

  1. Avijit Ghorui says:

    Nice article. Excellent demonstration by very simple words.

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: