0

I want to convert\map an existing object to IEnumerable<KeyValuePair<String, String>> where the key the name of the given property is and the value the value of the given property.

I found this, but this does not quite fit into my scenario: automapper

I did this:

List<KeyValuePair<String, Object>> list = new List<KeyValuePair<String, Object>>();

foreach (var prop in genericType.GetType().GetProperties())
{
    list.Add(new KeyValuePair<String, Object>(prop.Name, prop.GetValue(genericType, null)));
}

Is there a way without using reflection,if so how ?(genericTypeis a Type I know of)

Community
  • 1
  • 1
kkkk00999
  • 179
  • 2
  • 13
  • 1
    "Is there a way without using reflection" -- sure, just write out everything explicitly: `new[] { new KeyValuePair("Prop1", o.Prop1), new KeyValuePair("Prop2", o.Prop2), ... }`. But that's a lot more keystrokes. What's your beef with reflection in this case? – Jeroen Mostert Apr 14 '16 at 12:04
  • @Jeroen Mostert it should be more automatic, because sometimes its a different object, but thxs – kkkk00999 Apr 14 '16 at 12:39

1 Answers1

1

There is no way to do so without reflection. Here is the ToDictionary method that we use for that:

/// <summary>
///     Gets all public properties of an object and and puts them into dictionary.
/// </summary>
public static IDictionary<string, object> ToDictionary(this object instance)
{
    if (instance == null)
        throw new NullReferenceException();

    // if an object is dynamic it will convert to IDictionary<string, object>
    var result = instance as IDictionary<string, object>;
    if (result != null)
        return result;

    return instance.GetType()
        .GetProperties()
        .ToDictionary(x => x.Name, x => x.GetValue(instance));
}
Dmitri Trofimov
  • 753
  • 3
  • 14
  • you should throw an `ArgumentNullException` in this case. – Amit Kumar Ghosh Apr 14 '16 at 12:26
  • I haven't seen any convention on this, so I chose `NullReferenceException` based on method usage. I would normally expect `nullObject.SomeMethodCall()` throw a `NullReferenceException` rather than `ArgumentNullException`. – Dmitri Trofimov Apr 14 '16 at 12:34
  • `if(instance == null)` is not similar to `instance.SomeMethod()`.The latter can cause a possible `NullReferenceException` while the first cannot. – Amit Kumar Ghosh Apr 14 '16 at 12:36
  • This is an extension method and when used like `nullObject.ToDictionary()` it should throw `NullReferenceException`, shouldn't it? :) – Dmitri Trofimov Apr 14 '16 at 12:38
  • You can check `if (subMember is IEnumerable) {...}`. What is your goal? Are you trying to serialize the object? – Dmitri Trofimov Apr 18 '16 at 07:46