Object properties to dictionary converter
public static class ObjectExtensions { public static Dictionary<string, object> GetPropertyDictionary(this object source) { var properties = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); var result = properties.ToDictionary(propertyInfo => propertyInfo.Name, propertyInfo => propertyInfo.GetValue(source)); return result; } }Example:
var t = new { Bingo = true, Bango = "Test", Bongo = new DateTime(2015, 02, 05) }; var propertyDictionary = t.GetPropertyDictionary(); foreach (var o in propertyDictionary) { Debug.WriteLine(o.Key + " : " + o.Value + " [" + o.Value.GetType().Name + "]"); } //Returns //Bingo : True [Boolean] //Bango : Test [String] //Bongo : 05-02-2015 00:00:00 [DateTime]
Description
Takes all public properties of any object and inserts then into a dictionary
Details
- Author: Lasse Sjørup
- Submitted on: 2/9/2015 1:18:52 PM
- Language: C#
- Type: object
- Views: 2413
Double click on the code to select all.