Created
May 28, 2013 09:07
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | |
| }; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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