I have an object User:
public class User
{
public String Name { get; set; }
public String Name2 { get; set; }
public String Name3 { get; set; }
}
Also I have a Key Value set of strings that I want to assign to the object’s properties when I create it:
'Name':'srgrgsdfsdf'
'Name3':'dsfdsfafafd'
'Name2':'dtewtwerwer'
'Name4':'546353452552'
Now I create my object like this
User user = new User();
user.Name = "zzxasdas";
The problem is that I want to be able to assign the Key/Value data dynamically. This means that some of the items can be missing or the order may be different.
How can I check the name of the object properties dynamically and compare it with the Key like this:?
foreach [key] in Key/Value
if [user] has property named [key]
add [value] to [user] property with the name [key]
You would need to use Reflection to do this.
In particular,
Type.GetPropertiesorType.GetPropertywill allow you to discover information about the properties defined on a type, and get or set their values.This might look something like: