ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Object properties to dictionary converter

Takes all public properties of any object and inserts then into a dictionary

Source

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]

Author: Lasse Sjørup

Submitted on: 9 feb. 2015

Language: C#

Type: object

Views: 5664