Reputation: 3869
What the best way convert this dictionary:
Dictionary<string, object> person = new Dictionary<string, object>();
person.Add("ID", 1);
person.Add("Name", "Alex");
to object:
public class Person
{
public int ID{get;set;}
public string Name{get;set;}
}
?
Upvotes: 0
Views: 366
Reputation: 134811
If you want to be able to do this for any object in general, you could use reflection. Assuming the values in the dictionary are the appropriate type and requires no conversion:
static T GetObject<T>(Dictionary<string, object> dict)
where T : new()
{
var obj = new T();
foreach (var property in typeof(T).GetProperties())
{
var args = new object[1];
var setter = property.GetSetMethod(); // property has a public setter
if (setter != null && dict.TryGetValue(property.Name, out args[0]))
setter.Invoke(obj, args);
}
return obj;
}
Then to use it:
var alexDict = new Dictionary<string, object>
{
{ "ID", 1 },
{ "Name", "Alex" },
};
var alexPerson = GetObject<Person>(alexDict);
Upvotes: 2
Reputation: 12458
Here is my suggestion:
var newPerson = new Person
{
ID = (int)person["ID"],
Name = person["Name"].ToString()
};
This has no error handling and is assuming that the fields exists in the dictionary and are filled with valid values!
Upvotes: 4
Reputation: 1
The easy way:
var person = new Person
{
Id = (int)dict["ID"],
Name = (string)dict["Name"]
}
The generic way: use reflection.
Upvotes: 0
Reputation: 14668
Person myPerson = new Person();
myPerson.ID = (int)person["ID"];
myPerson.Name = (string)person["Name"];
Provides no error checking with the int cast.
Upvotes: 0