-1

I have a question. How to convert IDictionary<string, object> to class? As well as the create user account.

WebSecurity.CreateUserAndAccount(UserName, Password, new { eny = 0 , eny2 = "sas"});

And I have

void Create(String name, IDictionary<string, object> values)) {...}

and class

 class test {
    String name,
    int eny,
    int eny2
  }

I want to have a object test with data from dictionary.

Saurabh
  • 71,488
  • 40
  • 181
  • 244
user1644160
  • 277
  • 2
  • 6
  • 12
  • Not sure with the way this is worded, but are you asking 2 questions? Please try to explain yourself better. What exactly are you asking and what class do you want to convert your `IDictionary<>` too? – psubsee2003 Dec 05 '12 at 09:47
  • 3
    My guess: the OP wants to create and/or instantiate a class (important to know which), where the properties are created/filled from a dictionary (key=property name, value=property value). – Hans Kesting Dec 05 '12 at 10:32

1 Answers1

37

I'll make a guess

Dictionary<string, object> values = new Dictionary<string, object>()
{
    {"Name","Joe"},{"Id",123}
};

var test = GetObject<TestClass>(values);

class TestClass
{
    public string Name { get; set; }
    public int Id { get; set; }
}

T GetObject<T>(Dictionary<string,object> dict)
{
    Type type = typeof(T);
    var obj = Activator.CreateInstance(type);

    foreach (var kv in dict)
    {
        type.GetProperty(kv.Key).SetValue(obj, kv.Value);
    }
    return (T)obj;
}
L.B
  • 114,136
  • 19
  • 178
  • 224
  • Can't we use deserialization (for example dictionary->Json->Deserialize to specific class) in this case ? And will It be faster, what do you think ? – Tigran Petrosyan Oct 01 '20 at 11:04
  • Can't get it to work. I get for the kv.Key that I know is valid, a null. I can take dict["data"] (data is the key) and see the Json clearly. But it is 80 of the type I want so I should get a list of these. Or at least 1 of them. type.GetProperty(kv.Key) returns a null. kv.Key is "data". I can take dict[kv.Key] in the immediate window and get the Json string, which I want to cast into a list of objects. So, my T needs to be List and return needs to be return (List)obj but if GetProperty is returning NULL I can't get there. – user1585204 Jul 09 '21 at 19:53