0

I have a dictionary <Key, value> which needs to be populated to a C# class. C# property names will be same as key from dictionary and need to assign value from dictionary to properties. How can I do that dynamically ?

var dict = new Dictionary<String, String>();

dict.Add(firstname, "David");
dict.Add(lastname, "Paul");
dict.Add(address, "123 Lincoln Ave");
dict.Add(state, "CA");
dict.Add(zipcode, "84844");

public class sample
{
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string address { get; set; }
    public string zipcode { get; set; }
    public string state { get; set; }
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
msbyuva
  • 3,467
  • 13
  • 63
  • 87
  • 2
    Using JSON serialization, using reflection, using a dynamic object... What have you found and what other requirements do you have? – CodeCaster Oct 04 '22 at 13:25
  • 1
    Where is this `Dictionary` coming from? This smells of an [XY Problem](https://xyproblem.info/). Tell us what led you to believe this is the solution you need. – Xerillio Oct 04 '22 at 13:29
  • Probably you meant `dict.Add("firstname", ... dict.Add("lastname", ...` otherwise this question is much harder – BurnsBA Oct 04 '22 at 14:39

2 Answers2

0

I think for your solution it would be better to create a C# class called "Employees" for example, with these attributes from your "sample" class and instantiate new objects from it, adding them to a List<Employees> or in an array, you would be able to access the data from them.

I don't see much use for a Dictionary in this case. Let me know if it helps you! Good luck!

fuba
  • 23
  • 5
0

Try following :

            var dict = new Dictionary<String, String>();

            dict.Add("firstname", "David");
            dict.Add("lastname", "Paul");
            dict.Add("address", "123 Lincoln Ave");
            dict.Add("state", "CA");
            dict.Add("zipcode", "84844");

            sample sample = new sample() { firstname = dict["firstname"], lastname = dict["lastname"], address = dict["address"], zipcode = dict["zipcode"], state = dict["state"] };
   
jdweng
  • 33,250
  • 2
  • 15
  • 20