Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

A usefull Dictionary extension

4.00/5 (2 votes)
26 Mar 2012CPOL 16K  
A simple extension to map ditionary entries using lambda expressions

Introduction 

Initializing dictionaries is a pain in the neck. I've seen many clever ways to make it painless. Here goes  yet another one.  

This it's not my idea, I saw it a couple of days ago in some API but I can't remember where. This is my very simple implementation.  

The extension   

 
public static IDictionary<string, TValue> Map<TValue>(this IDictionary<string, TValue> 
	dictionary, Expression<Func<object, TValue>> pair)
{
	var key = pair.Parameters[0].Name;
	var eval = pair.Compile().Invoke(new object[1]);

	dictionary[key] = eval;

	return dictionary;
}   

Still we'll need some guard clauses and clean up. 

Using it 

C++
var bag = new Dictionary<string, object>()
    .Map(Id => 1)
    .Map(Name => "Tom Bombadil")
    .Map(CreatedOn => DateTime.Today)
    .Map(CreatedBy => "root");

Assert.That(bag["Id"], Is.EqualTo(1));
Assert.That(bag["Name"], Is.EqualTo("Tom Bombadil"));
Assert.That(bag["CreatedOn"], Is.EqualTo(DateTime.Today));
Assert.That(bag["CreatedBy"], Is.EqualTo("root")); 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)