c# map dictionary to object properties code example
Example 1: c# dictionary values to array
// dict is Dictionary<string, Foo>
Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);
// or in C# 3.0:
var foos = dict.Values.ToArray();
Example 2: mapping dictionary to object c#
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace WebOpsApi.Shared.Helpers
{
public static class MappingExtension
{
public static T ToObject<T>(this IDictionary<string, object> source)
where T : class, new()
{
var someObject = new T();
var someObjectType = someObject.GetType();
foreach (var item in source)
{
var key = char.ToUpper(item.Key[0]) + item.Key.Substring(1);
var targetProperty = someObjectType.GetProperty(key);
if (targetProperty.PropertyType == typeof (string))
{
targetProperty.SetValue(someObject, item.Value);
}
else
{
var parseMethod = targetProperty.PropertyType.GetMethod("TryParse",
BindingFlags.Public | BindingFlags.Static, null,
new[] {typeof (string), targetProperty.PropertyType.MakeByRefType()}, null);
if (parseMethod != null)
{
var parameters = new[] { item.Value, null };
var success = (bool)parseMethod.Invoke(null, parameters);
if (success)
{
targetProperty.SetValue(someObject, parameters[1]);
}
}
}
}
return someObject;
}
public static IDictionary<string, object> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
{
return source.GetType().GetProperties(bindingAttr).ToDictionary
(
propInfo => propInfo.Name,
propInfo => propInfo.GetValue(source, null)
);
}
}
}
Example 3: c# map dictionary to object properties
class ObjectToMapTo
{
public int ID;
public string Name;
public bool IsAdmin;
public override string ToString()
{
return $"(ID={ID} Name={Name} IsAdmin={IsAdmin})";
}
}
static object MapDictToObj(Dictionary<string, object> dict, Type destObject)
{
object returnobj = Activator.CreateInstance(destObject);
foreach (string key in dict.Keys)
{
object value = dict[key];
FieldInfo field = destObject.GetField(key);
if (field != null)
{
field.SetValue(returnobj, value);
}
}
return returnobj;
}
static void Main(string[] args)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict["ID"] = 1000;
dict["Name"] = "This is a name";
dict["IsAdmin"] = true;
ObjectToMapTo obj = (ObjectToMapTo)MapDictToObj(dict, typeof(ObjectToMapTo));
Console.WriteLine(obj);
Console.ReadKey();
//Returns: (ID=1000 Name=This is a name IsAdmin=True)
}