Skip to content

Instantly share code, notes, and snippets.

@mjul
Created May 28, 2013 09:07
Show Gist options
  • Select an option

  • Save mjul/5661502 to your computer and use it in GitHub Desktop.

Select an option

Save mjul/5661502 to your computer and use it in GitHub Desktop.
Using C# dynamic type to navigate a dictionary via dynamically generated properties corresponding to the dictionary's keys.
protected override University MapFromRow(Row input)
{
// Using dynamic so we can hit the TryGetMember on Row to look up
// missing properties (here: all of them) in the key-value map.
dynamic row = input;
return new University()
{
UniversityNumber = Int32.Parse(row.UniversityNumber),
Name = row.UniversityName,
};
}
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Linq;
namespace DynamicDotting
{
// A row functions like an expando object, it gets the properties
// corresponding to the keys in the key-values it is constructed from.
// You can then dot on it to extract the value for a key, e.g. the name
// dynamic row = new Row(...);
// var name = row.Name; // looks up the value under the key Name
public class Row : DynamicObject
{
private readonly Dictionary<string,string> _data;
public Row()
{
_data = new Dictionary<string, string>();
}
public Row(IEnumerable<KeyValuePair<string, string>> kvs)
{
_data = kvs.ToDictionary(kv => CanonicalKey(kv.Key), kv => kv.Value);
}
private string CanonicalKey(string key)
{
return Regex.Replace(key.ToLower(), "[^a-z0-9_]", String.Empty);
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var canonicalKey = CanonicalKey(binder.Name);
result = _data[canonicalKey];
return _data.ContainsKey(canonicalKey);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment