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

ToDictionary<>

Converts any object to a dictionary

Source

/// <summary>
/// Convert the object properties to a dictionary
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static IDictionary<string, object> ToDictionary(this object source)
{
    return source.ToDictionary<object>();
}

/// <summary>
/// Converts the object properties to a dictionary
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static IDictionary<string, T> ToDictionary<T>(this object source)
{
    if (source == null)
        ThrowExceptionWhenSourceArgumentIsNull();

    var dictionary = new Dictionary<string, T>();
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
        AddPropertyToDictionary<T>(property, source, dictionary);

    return dictionary;
}

private static void AddPropertyToDictionary<T>(PropertyDescriptor property, object source, Dictionary<string, T> dictionary)
{
    object value = property.GetValue(source);
    if (IsOfType<T>(value))
    {
        dictionary.Add(property.Name, (T)value);
    }
    else
    {
        T newValue = (T)Convert.ChangeType(value, typeof(T));
        dictionary.Add(property.Name, newValue);
    }
}

private static bool IsOfType<T>(object value)
{
    return value is T;
}

private static void ThrowExceptionWhenSourceArgumentIsNull()
{
    throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
}

Example

class MyClass
{
    public MyClass()
    {
        MyProperty = "Value 1";
        MyProperty2 = "Value 2";
        MyInt = 2;
    }

    public string MyProperty { get; set; }
    public string MyProperty2 { get; set; }
    public int MyInt { get; set; }
}

[TestMethod]
public void Test_ObjectToDictionary()
{
    MyClass _Object = new MyClass();
    IDictionary<string, string> dic 
        = _Object.ToDictionary<string>();
}

Author: mInternauta

Submitted on: 1 mei 2016

Language: C#

Type: IDicitionary

Views: 6064