Skip to content

Instantly share code, notes, and snippets.

@adamalesandro
Created March 7, 2017 22:33
Show Gist options
  • Save adamalesandro/9d54cd67f65ac47240fab22facc8fe2b to your computer and use it in GitHub Desktop.
Save adamalesandro/9d54cd67f65ac47240fab22facc8fe2b to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var values = new List<Dictionary<string, object>>()
{
new Dictionary<string, object>()
{
{"Name","Adam"},
{ "Id",123},
{ "Human", 1 }
},
new Dictionary<string, object>()
{
{"Name","Lancy"},
{ "Id",456},
{ "Human", 0 }
}
};
var objs = GetObjects<TestClass>(values);
//Console.WriteLine(objs.Name);
foreach (var person in objs)
{
Console.WriteLine(person.Name);
Console.WriteLine(person.Human);
}
Console.ReadLine();
}
static List<T> GetObjects<T>(List<Dictionary<string, object>> results)
{
Type type = typeof(T);
var list = new List<T>();
foreach(var dict in results)
{
list.Add(GetObject<T>(dict));
}
return list;
}
static T GetObject<T>(IDictionary<string, object> dict)
{
Type type = typeof(T);
var obj = Activator.CreateInstance(type);
foreach (var keyvalue in dict)
{
type.GetProperty(keyvalue.Key).SetValue(obj, keyvalue.Value);
}
return (T)obj;
}
}
class TestClass
{
public string Name { get; set; }
public int Id { get; set; }
public bool Human { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment