Created
February 8, 2018 21:58
-
-
Save dandohotaru/298282930ef6cd7b686b46d270ea5faa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var persons = new[] | |
{ | |
new Person{Id= 1, Name="John Doe", Age=21}, | |
new Person{Id= 2, Name="Jane Doe", Age=22}, | |
new Person{Id= 3, Name="Jim Doe", Age=23}, | |
}; | |
var map = new Func<Person, dynamic>(person => | |
{ | |
var result = person.ToDynamic(); | |
result.Uuid = Guid.NewGuid(); | |
return result; | |
}); | |
var results = persons | |
.Select(p => map(p)) | |
.ToList(); | |
results.Dump(); | |
var json = JsonConvert.SerializeObject(results); | |
json.Dump(); | |
} | |
class Person | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
public int Age { get; set; } | |
} | |
public static class Extensions | |
{ | |
public static dynamic ToDynamic(this object value) | |
{ | |
IDictionary<string, object> expando = new ExpandoObject(); | |
var properties = TypeDescriptor.GetProperties(value.GetType()); | |
foreach (PropertyDescriptor property in properties) | |
{ | |
expando.Add(property.Name, property.GetValue(value)); | |
} | |
return expando as ExpandoObject; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment