Hash
The Hash class provides a lambda-based syntax for creating dictionaries. For example, to create an IDictionary instance you could use the following code:
IDictionary dictionary = new Hash(id => "foo", @class => "bar", name => "foobar");
Which would be the equivalent of:
IDictionary dictionary = new HybridDictionary();
dictionary.Add("id", "foo");
dictionary.Add("class", "bar");
dictionary.Add("name", "foobar");
You can use a similar syntax to create strongly-typed Dictionary<TKey, TValue> instances by using the Hash<T> instead:
IDictionary<string, string> dictionary = new Hash<string>(id => "foo", @class => "bar", name => "foobar");
Which would be the equivalent of:
IDictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("id", "foo");
dictionary.Add("class", "bar");
dictionary.Add("name", "foobar");
Note that both versions of Hash create a case-insensitive dictionary.
Dictionary Extension Methods
The DictionaryExtensions class provides an Add method to all IDictionary and IDictionary<TKey, TValue> instances that allow you to add items to existing dictionary instances using the lambda-based syntax. Note that you need to add a using directive for the
MvcContrib namespace for these extension methods to appear.
IDictionary hashtable = new Hashtable();
hashtable.Add(id => "foo", name => "bar");
Limitations
The Hash object will not work correctly inside Linq expressions (or any Expression<T>) as access to the key names is lost.