Sunday, July 31, 2011

Creating a composite key in your container

If you need to create a composite key (for a dictionary for example) where the natural key could come from multiple sources a standard technique is to prepend the source to the natural key to ensure that it is unique. However, this can still cause duplicate keys so to solve this problem you should always add a delimiter between any concatenations that you do.

The problem is easily illustrated by looking at how files are managed in folders. Typically the composite key is the fully directory path and file name which identifies the file you are looking for. The delimiter is the backslash.

Say you had 2 files: bat.txt and mybat.txt

Let's say that they were in 2 directories:
c:\temp\somy and c:\temp\so

Without those backslashes we would have:
giving us the same key.

So in code you may have:

public void AddItem(string source, string itemName,
  object data, Dictionary<string, object> myDictionary)
     string compositeKey = source + "+" + itemName;
     myDictionary.Add(compositeKey, data);

No comments:

Post a Comment